Home  >  Article  >  Web Front-end  >  Explanation of issues you need to pay attention to when using jQuery selectors

Explanation of issues you need to pay attention to when using jQuery selectors

伊谢尔伦
伊谢尔伦Original
2017-06-17 16:51:422850browse

一、选择器中含有特殊符号的注意事项

1.选择器中含有“.”、“#”、“(”或“]”等特殊字符

根据W3C的规定,属性值中是不能含有这些特殊字符的,但在实际项目中偶尔会遇到表达式中含有“#”和“.”等特殊字符,如果按照普通的方式去处理出来的话就会出错。解决此类错误的方法是使用转义符转义。

<div id="id#b">bb</div>  
<div id="id[1]">cc</div>

不能这样写:

$(&#39;#id#b&#39;);  $(&#39;#id[1]&#39;);

应该使用转义符号:

$(&#39;#id\\#b&#39;);       //转义特殊字符“#”  
$(&#39;#id\\[1\\]&#39;);    //转义特殊字符“[ ]”

2.属性选择器的引号问题
1.3.1版本彻底放弃了1.1.0版本遗留下的@符号,如果你使用1.3.1以上的版本,那么你不能在属性前添加@符号,比如:

$(&#39;div[title="test"&#39;];

二、选择器中含有空格的注意事项

选择器中的空格也是不容忽视的,多一个空格或少一个空格也许会得到截然不同的结果。看下面这个例子,它的HTML代码如下:

<div class="test">  
  <div style="display:none;">aa</div>  
  <div style="display:none;">bb</div>  
  <div style="display:none;">cc</div>  
  <div class="test" style="display:none;">dd</div>  
</div>  
<div class="test" style="display:none;">ee</div>  
<div class="test" style="display:none;">ff</div>

使用如下的jQuery选择器分别获取它们。
//注意区分类似这样的选择器  
//虽然一个空格,却截然不同的效果.

var $t_a = $(&#39;.test :hidden&#39;);  
var $t_b = $(&#39;.test:hidden&#39;);  
var len_a = $t_a.length;  
var len_b = $t_b.length;  
alert("$(&#39;.test :hidden&#39;) = "+len_a);  //输出 4    
alert("$(&#39;.test:hidden&#39;) = "+len_b);  //输出 3

之所以会出现不同的结果,是因为后代选择器与过滤选择器的不同。  

var $t_a = $('.test :hidden');   //有空格 是选取class为“test”的元素里面的隐藏元素。
var $t_b = $('.test:hidden');   //没有空格 则是选取隐藏的class为“test”的元素。
这点和css是一样的 css中假如有个div有两个class属性.top 和 .right 6b776e95171664370935a502f42fd09016b28748ea4df4d9c2150843fecfba68,在css中我们要选择它定义样式只能这样写 .top.right{  } 而不能写成.top .right{ }

jquery选择器结果是数组时需要主要的一个问题,并详细分析了产生此问题的原因:

$("#div1 span")获得三个对象的数组

1.如果执行 $("#div1 span").html("aaa"),则数组内的所有对象都会改变

2.如果执行$("#div1 span").html(),只取值的话,则只会取数组第一个对象的值

所以如果选择器获得是一个数组,要对数组每个元素都进行操作时,最好用each().

The above is the detailed content of Explanation of issues you need to pay attention to when using jQuery selectors. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn