2008-09-18 5 views
33

특성에 사용자 정의 네임 스페이스를 사용하는 간단한 XHTML 문서가 있다고 가정합니다.jQuery 특성 선택자 : 사용자 지정 네임 스페이스가있는 특성을 쿼리하는 방법

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

jQuery를 사용하여 특정 사용자 지정 특성을 가진 각 요소를 어떻게 대응시킬 수 있습니까?

$("div[custom:attr]") 
사용

가 작동하지 않습니다. (파이어 폭스 만 사용해 보았는데, 지금까지는.)

+0

업데이트, Suphi의 대답은 매우 간단 구문과 작품입니다. 그래도 성능 비교는하지 않았습니다. –

+0

네임 스페이스 접두사 선언은 xmlns : custom =입니까? – grantwparks

답변

42

('사용자 정의 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.'); 
}); 
+0

나는 그런 것을 두려워했다. 감사! –

3

여기 http://pastebin.me/48d233d998b4b

기본적으로는 $ ('DIV') ATTR 찾습니다. : jQuery를 직접 사용자 정의 네임 스페이스를 지원하지 않습니다

+1

나는 내 questin을 명확히했다. 나는 속성의 값을 얻지 않고, 커스텀 속성을 가진 각 요소를 일치시키고 싶다. –

+0

@redsquare : 이것은 대부분의 브라우저에서 작동하지만 Opera에서는 실패합니다. 그것에 대한 어떤 빠른 수정? – Gapipro

19

이 어떤 조건에서 작동합니다

$("div[custom\\:attr]")

그러나, 더 진보 된 방법에 대한 속성에 일치하는 this XML Namespace jQuery plug-in

+0

네임 스페이스 플러그인은 꿈입니다. –

+0

이 전략은 Safari 및 Chrome과 같은 Webkit 기반 브라우저에서 작동하지 않습니다. 어떤 생각? – kaychaks

+1

+1, 작은 쪽 메모가 붙어 있습니다 : jQuery는 추가 된 XML 청크의 네임 스페이스 정의를 HTML (사실상 SVG로 테스트)에서 벗어납니다. 아마도 HTML이 (일반적으로?)'xmlns' 속성을 인정하지 않기 때문에'xmlns : custom = "uri"'속성을'custom = "uri"'로 mangle합니다. 문서를 XHTML로 제공하면 문제가 해결되지만 모든 경우에 실용적이지는 않습니다. –

7

구문을 볼 수있다 :

$ ("div [customattr = bla]") 와 (과) 일치하는 --div customattr = "bla"-

,

$ ("[customattr]") 일치 "를 customattr"속성을 가진 모든 태그 네임 스페이스

처럼 속성 : 당신이 좋은 개요를 찾을 수는 여기에

작동하지 '사용자 정의 ATTR' http://www.pamaya.com/jquery-selectors-and-attribute-selectors-reference-and-examples/

+0

링크 된 기사가 사용자 지정 특성을 참조하지 않습니다. –

+2

이것은 답변이 아닙니다. 기본적으로 질문을 다시하고 선택자가 네임 스페이스에서 작동하지 않는 것 같다고 말합니다. – spaaarky21

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(); 
관련 문제