2011-04-14 124 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")); 
     });