2011-04-14 159 views
1

鉴于以下代码,我期望有一个“searchRes1”的警报,它是id的直接匹配,对于第二个块,我期望它提醒其他两个div,因为id包含“搜索”。我错过了什么?JQuery:属性选择器不能按预期工作

  <div id="sRes"> 
       <h4>Search for things</h4> 
       <div id="searchRes1">123</div> 
       <div id="searchRes2">456</div> 
       <div id="searchRes3">789</div> 
      </div> 
      <script> 
       $("#sRes div[id='searchRes1']").each(function() { 
        alert($(this).attr("id")); 
       }); 

       $("#sRes div[id~='search']").each(function() { 
        alert($(this).attr("id")); 
       }); 
      </script> 
+0

是什么警报在第二选择? – yoavmatchulsky 2011-04-14 05:49:47

回答

2

在CSS选择器,包含~=)指包含完整的字。这对于rel="foo bar"这样的东西可能是有用的,其将与rel~='foo',rel~='bar'匹配,但不匹配rel~='fo'

尝试startsWith^=):

$("#sRes div[id^='search']") 

http://www.w3.org/TR/css3-selectors/#attribute-selectors

+0

+1我测试了这个。有用。 – 2011-04-14 06:07:50

+0

打我吧:P – corroded 2011-04-14 06:11:17

+0

好吧,这个作品...我应该仔细阅读文档,因为它明确指出: 这个选择器将测试字符串与属性值中的每个字匹配,其中“字”被定义为由空白分隔的字符串。如果测试字符串与任何字词完全相同,则选择器匹配。 失败的用户错误。谢谢! – 2011-04-14 21:29:37

0

ü错过了名,还可以使用!~

$("#sRes div[id!='searchRes1']").each(function() { 
        alert($(this).attr("id")); 
       }); 

DEMO

Reference

1

第一个是我http://jsfiddle.net/raW26/

做工精细而为second一个工作,我想的属性,你正在选择必须用空格分隔

您必须使用*=^=才能正常工作

P.S.你不需要使用$(this).attr("id")只是this.id足够

$("#sRes div[id='searchRes1']").each(function() { 
      alert($(this).attr("id")); 
     }); 

     $("#sRes div[id*='search']").each(function() { 
      alert($(this).attr("id")); 
     }); 
相关问题