다음은 나를 위해 작동하는 사용자 지정 선택기의 구현입니다.
// 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();
업데이트, Suphi의 대답은 매우 간단 구문과 작품입니다. 그래도 성능 비교는하지 않았습니다. –
네임 스페이스 접두사 선언은 xmlns : custom =입니까? – grantwparks