Javascript jQuery属性选择器:如何使用自定义名称空间查询属性
假设我有一个简单的XHTML文档,它使用自定义名称空间作为属性:Javascript jQuery属性选择器:如何使用自定义名称空间查询属性,javascript,jquery,Javascript,Jquery,假设我有一个简单的XHTML文档,它使用自定义名称空间作为属性: <html xmlns="..." xmlns:custom="http://www.example.com/ns"> ... <div class="foo" custom:attr="bla"/> ... </html> 不起作用。(目前仅在Firefox上试用过。)您应该使用$('div')。attr('custom:attr')不直接支持自定义名称空间,但您可以
<html xmlns="..." xmlns:custom="http://www.example.com/ns">
...
<div class="foo" custom:attr="bla"/>
...
</html>
不起作用。(目前仅在Firefox上试用过。)您应该使用$('div')。attr('custom:attr')
不直接支持自定义名称空间,但您可以通过使用筛选函数来查找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.');
});
这在某些情况下有效:
$(“div[custom\\\:attr]”)
但是,有关更高级的方法,请参见按属性匹配的语法为:
$(“div[customattr=bla]”)匹配div customattr=“bla”
$(“[customattr]”
匹配具有属性的所有标记“customattr”
使用诸如'custom:attr'
之类的名称空间属性,它不起作用
您可以找到一个很好的概述。这里是一个自定义选择器的实现,它适合我
// 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();
我澄清了我的问题:我想匹配每个具有自定义属性的元素,而不是获取属性的值。@redsquare:这适用于大多数浏览器,但在Opera中失败。有什么快速解决方法吗?命名空间插件是一个梦想。这种策略在Safari和Chrome等基于Webkit的浏览器中不起作用。有什么想法吗?+1,还有一点旁注:jQuery将删除附加XML块的命名空间定义,而不是HTML(实际上是用SVG测试的)。它将属性xmlns:custom=“uri”
转换为custom=“uri”
,可能是因为HTML(通常)不承认xmlns
属性。将文档作为XHTML提供解决了这个问题,但并非在所有情况下都可行。根据我的经验,通常是浏览器本身负责破坏HTML(因为它管理DOM,而不是jQuery)。IE在这方面尤其糟糕(令人大吃一惊)。更新,Suphi的答案是一个更简单的语法,并且可以工作。但是我没有做任何性能比较。命名空间前缀声明应该是xmlns:custom=?链接的文章没有引用自定义属性。这不是答案。它基本上只是重复这个问题,并说选择器似乎不适用于名称空间。
// 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();