[javascript] jQuery 객체에서 선택기를 어떻게 얻을 수 있습니까?

$("*").click(function(){
    $(this); // how can I get selector from $(this) ?
});

선택기$(this)얻는 쉬운 방법이 있습니까? 선택기로 요소를 선택하는 방법이 있지만 요소에서 선택자를 가져 오는 것은 어떻습니까?



답변

좋아요, 질문 위의 주석에서 질문자 Fidilip는 그가 실제로 추구 하는 것은 현재 요소의 경로를 얻는 것입니다.

다음은 DOM 상위 트리를 “등반”한 다음 클릭 한 항목의 id또는 class속성을 포함하여 상당히 구체적인 선택기를 구축하는 스크립트입니다 .

jsFiddle에서 작동하는 것을보십시오 : http://jsfiddle.net/Jkj2n/209/

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
    $(function() {
        $("*").on("click", function(e) {
          e.preventDefault();
          var selector = $(this)
            .parents()
            .map(function() { return this.tagName; })
            .get()
            .reverse()
            .concat([this.nodeName])
            .join(">");

          var id = $(this).attr("id");
          if (id) {
            selector += "#"+ id;
          }

          var classNames = $(this).attr("class");
          if (classNames) {
            selector += "." + $.trim(classNames).replace(/\s/gi, ".");
          }

          alert(selector);
      });
    });
    </script>
</head>
<body>
<h1><span>I love</span> jQuery</h1>
<div>
  <p>It's the <strong>BEST THING</strong> ever</p>
  <button id="myButton">Button test</button>
</div>
<ul>
  <li>Item one
    <ul>
      <li id="sub2" >Sub one</li>
      <li id="sub2" class="subitem otherclass">Sub two</li>
    </ul>
  </li>
</ul>
</body>
</html>

예를 들어 아래 HTML에서 두 번째 목록 중첩 목록 항목을 클릭하면 다음과 같은 결과가 나타납니다.

HTML>BODY>UL>LI>UL>LI#sub2.subitem.otherclass


답변

:: WARNING ::
.selector는 버전 1.7에서 더 이상 사용되지 않으며 1.9에서 제거되었습니다.

jQuery 객체에는 어제 코드를 파헤칠 때 본 선택기 속성이 있습니다. 문서에 정의되어 있는지 여부가 (향후 교정을 위해) 얼마나 신뢰할 수 있는지 모릅니다. 하지만 작동합니다!

$('*').selector // returns *

편집 : 이벤트 내에서 선택기를 찾으려면 요소가 다양한 선택기를 통해 할당 된 여러 클릭 이벤트를 가질 수 있으므로 해당 정보는 요소가 아닌 이벤트 자체의 일부 여야합니다. 해결책은 주위에 래퍼를 사용하는 것 bind(), click()직접 추가하는 대신 이벤트를 추가하는 등.

jQuery.fn.addEvent = function(type, handler) {
    this.bind(type, {'selector': this.selector}, handler);
};

선택기가라는 개체의 속성으로 전달됩니다 selector. 로 액세스하십시오 event.data.selector.

일부 마크 업 ( http://jsfiddle.net/DFh7z/ ) 에서 시도해 보겠습니다 .

<p class='info'>some text and <a>a link</a></p>​

$('p a').addEvent('click', function(event) {
    alert(event.data.selector); // p a
});

면책 조항 : live()이벤트 와 마찬가지로 DOM 순회 메서드를 사용하면 selector 속성이 유효하지 않을 수 있습니다.

<div><a>a link</a></div>

live이 경우 a.parent()유효하지 않은 선택자인 선택자 속성에 의존 하므로 아래 코드는 작동하지 않습니다 .

$('a').parent().live(function() { alert('something'); });

우리의 addEvent메서드가 실행되지만 잘못된 선택기가 표시됩니다 a.parent().


답변

@drzaus와 공동으로 다음과 같은 jQuery 플러그인을 만들었습니다.

jQuery.getSelector

!(function ($, undefined) {
    /// adapted http://jsfiddle.net/drzaus/Hgjfh/5/

    var get_selector = function (element) {
        var pieces = [];

        for (; element && element.tagName !== undefined; element = element.parentNode) {
            if (element.className) {
                var classes = element.className.split(' ');
                for (var i in classes) {
                    if (classes.hasOwnProperty(i) && classes[i]) {
                        pieces.unshift(classes[i]);
                        pieces.unshift('.');
                    }
                }
            }
            if (element.id && !/\s/.test(element.id)) {
                pieces.unshift(element.id);
                pieces.unshift('#');
            }
            pieces.unshift(element.tagName);
            pieces.unshift(' > ');
        }

        return pieces.slice(1).join('');
    };

    $.fn.getSelector = function (only_one) {
        if (true === only_one) {
            return get_selector(this[0]);
        } else {
            return $.map(this, function (el) {
                return get_selector(el);
            });
        }
    };

})(window.jQuery);

축소 된 자바 스크립트

// http://stackoverflow.com/questions/2420970/how-can-i-get-selector-from-jquery-object/15623322#15623322
!function(e,t){var n=function(e){var n=[];for(;e&&e.tagName!==t;e=e.parentNode){if(e.className){var r=e.className.split(" ");for(var i in r){if(r.hasOwnProperty(i)&&r[i]){n.unshift(r[i]);n.unshift(".")}}}if(e.id&&!/\s/.test(e.id)){n.unshift(e.id);n.unshift("#")}n.unshift(e.tagName);n.unshift(" > ")}return n.slice(1).join("")};e.fn.getSelector=function(t){if(true===t){return n(this[0])}else{return e.map(this,function(e){return n(e)})}}}(window.jQuery)

사용법과 고차

<html>
    <head>...</head>
    <body>
        <div id="sidebar">
            <ul>
                <li>
                    <a href="/" id="home">Home</a>
                </li>
            </ul>
        </div>
        <div id="main">
            <h1 id="title">Welcome</h1>
        </div>

        <script type="text/javascript">

            // Simple use case
            $('#main').getSelector();           // => 'HTML > BODY > DIV#main'

            // If there are multiple matches then an array will be returned
            $('body > div').getSelector();      // => ['HTML > BODY > DIV#main', 'HTML > BODY > DIV#sidebar']

            // Passing true to the method will cause it to return the selector for the first match
            $('body > div').getSelector(true);  // => 'HTML > BODY > DIV#main'

        </script>
    </body>
</html>

QUnit 테스트가있는 바이올린

http://jsfiddle.net/CALY5/5/


답변

이거 해봤 어?

 $("*").click(function(){
    $(this).attr("id");
 });


답변

jQuery 플러그인을 출시했습니다 : jQuery Selectorator , 이런 선택기를 얻을 수 있습니다.

$("*").on("click", function(){
  alert($(this).getSelector().join("\n"));
  return false;
});


답변

이 시도:

$("*").click(function(event){
    console.log($(event.handleObj.selector));
 });


답변

다음과 같이 $ 함수 위에 레이어를 추가하면됩니다.

$ = (function(jQ) {
	return (function() {
		var fnc = jQ.apply(this,arguments);
		fnc.selector = (arguments.length>0)?arguments[0]:null;
		return fnc;
	});
})($);

이제 다음과 같은 작업을 할 수 있습니다.

$ ( "a"). selector

최신 jQuery 버전에서도 “a”를 반환합니다.