2008-09-18 67 views
33

假設我有一個使用的屬性自定義命名空間的簡單XHTML文檔屬性:jQuery的屬性選擇:如何查詢與自定義空間

<html xmlns="..." xmlns:custom="http://www.example.com/ns"> 
    ... 
    <div class="foo" custom:attr="bla"/> 
    ... 
</html> 

如何具有一定的自定義每個元素匹配屬性使用jQuery?使用

$("div[custom:attr]") 

不起作用。 (試圖與Firefox而已,這麼遠。)

+0

更新,Suphi的回答是一個非常簡單的語法和作品。雖然我沒有做過任何性能比較。 – 2012-02-22 15:01:54

+0

命名空間前綴聲明應該是xmlns:custom =? – grantwparks 2012-05-05 23:31:41

回答

42

的jQuery並不直接支持自定義命名空間,但你可以通過使用過濾器功能找到你正在尋找的div。

// find all divs that have custom:attr 
$('div').filter(function() { return $(this).attr('custom:attr'); }).each(function() { 
    // matched a div with custom::attr 
    $(this).html('I was found.'); 
}); 
+0

我擔心這樣的事情。謝謝! – 2008-09-18 11:50:24

3

看這裏http://pastebin.me/48d233d998b4b

基本上它$( '格')ATTR。( '定製:ATTR')

+1

我澄清了我的問題:我想匹配每個具有自定義屬性的元素,而不是獲取屬性的值。 – 2008-09-18 11:24:03

+0

@redsquare:這適用於大多數瀏覽器,但在Opera中失敗。任何快速解決這個問題? – Gapipro 2011-10-21 08:30:52

2

這是一個自定義選擇器的實現,它適用於我。

// Custom jQuery selector to select on custom namespaced attributes 
$.expr[':'].nsAttr = function(obj, index, meta, stack) { 

    // if the parameter isn't a string, the selector is invalid, 
    // so always return false. 
    if (typeof meta[3] != 'string') 
     return false; 

    // if the parameter doesn't have an '=' character in it, 
    // assume it is an attribute name with no value, 
    // and match all elements that have only that attribute name. 
    if (meta[3].indexOf('=') == -1) 
    { 
     var val = $(obj).attr(meta[3]); 
     return (typeof val !== 'undefined' && val !== false); 
    } 
    // if the parameter does contain an '=' character, 
    // we should only match elements that have an attribute 
    // with a matching name and value. 
    else 
    { 
     // split the parameter into name/value pairs 
     var arr = meta[3].split('=', 2); 
     var attrName = arr[0]; 
     var attrValue = arr[1]; 

     // if the current object has an attribute matching the specified 
     // name & value, include it in our selection. 
     return ($(obj).attr(attrName) == attrValue); 
    } 
}; 

用法示例:

// Show all divs where the custom attribute matches both name and value. 
$('div:nsAttr(MyNameSpace:customAttr=someValue)').show(); 

// Show all divs that have the custom attribute, regardless of its value. 
$('div:nsAttr(MyNameSpace:customAttr)').show();