bestsource

jQuery 개체에서 셀렉터를 가져오려면 어떻게 해야 합니까?

bestsource 2023. 10. 16. 21:56
반응형

jQuery 개체에서 셀렉터를 가져오려면 어떻게 해야 합니까?

$("*").click(function(){
    $(this); // how can I get selector from $(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

고::
r는 1에서 더 사용되지 전 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(), traversal우 Selector다.

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

는 와 하지 않습니다.live이 합니다.a.parent() 않습니다 -r

$('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)

사용량 및 Gotchas

<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"); 
 });

시도해 보기:

$("*").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")
and will return "a" even on newer jQuery versions.

http://www.selectorgadget.com/ 은 이 사용 사례를 위해 명시적으로 설계된 북마크렛입니다.

그렇기는 하지만 CSS 셀렉터를 직접 배워야 한다는 점에서 대부분의 다른 사람들과 동의합니다. 코드로 셀렉터를 생성하는 것은 지속 가능하지 않습니다.:)

@jesegavin의 수정 사항에 몇 가지 수정 사항을 추가했습니다.

요소에 ID가 있으면 즉시 반환됩니다.요소에 ID, 클래스, 이름이 없는 경우 이름 속성 검사와 n-child 선택기도 추가했습니다.

이름은 페이지에 여러 양식이 있고 입력 내용이 비슷할 경우 범위를 지정해야 할 수도 있지만, 아직 처리하지 못했습니다.

function getSelector(el){
    var $el = $(el);

    var id = $el.attr("id");
    if (id) { //"should" only be one of these if theres an ID
        return "#"+ id;
    }

    var selector = $el.parents()
                .map(function() { return this.tagName; })
                .get().reverse().join(" ");

    if (selector) {
        selector += " "+ $el[0].nodeName;
    }

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

    var name = $el.attr('name');
    if (name) {
        selector += "[name='" + name + "']";
    }
    if (!name){
        var index = $el.index();
        if (index) {
            index = index + 1;
            selector += ":nth-child(" + index + ")";
        }
    }
    return selector;
}

jQuery 플러그인 jQuery Selectorator를 출시했습니다. 이렇게 선택할 수 있습니다.

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

위의 솔루션 이후에도 여러 요소를 얻고 있었기 때문에 더 많은 핀 포인팅 돔 요소를 위해 dds1024 작업을 확장했습니다.

예: DIV:nth-child (1) DIV:nth-child (3) DIV:nth-child (1) DIV:nth-child (1) DIV:nth-child (8) DIV:nth-child (2) DIV:nth-child (1) DIV:nth-child (2) DIV:nth-child (1) H4:nth-child (2)

코드:

function getSelector(el)
{
    var $el = jQuery(el);

    var selector = $el.parents(":not(html,body)")
                .map(function() { 
                                    var i = jQuery(this).index(); 
                                    i_str = ''; 

                                    if (typeof i != 'undefined') 
                                    {
                                        i = i + 1;
                                        i_str += ":nth-child(" + i + ")";
                                    }

                                    return this.tagName + i_str; 
                                })
                .get().reverse().join(" ");

    if (selector) {
        selector += " "+ $el[0].nodeName;
    }

    var index = $el.index();
    if (typeof index != 'undefined')  {
        index = index + 1;
        selector += ":nth-child(" + index + ")";
    }

    return selector;
}

여기에서 읽은 답변을 고려하여 다음과 같이 제안하고자 합니다.

function getSelectorFromElement($el) {
  if (!$el || !$el.length) {
    return ;
  }

  function _getChildSelector(index) {
    if (typeof index === 'undefined') {
      return '';
    }

    index = index + 1;
    return ':nth-child(' + index + ')';
  }

  function _getIdAndClassNames($el) {
    var selector = '';

    // attach id if exists
    var elId = $el.attr('id');
    if(elId){
      selector += '#' + elId;
    }

    // attach class names if exists
    var classNames = $el.attr('class');
    if(classNames){
      selector += '.' + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, '.');
    }

    return selector;
  }

  // get all parents siblings index and element's tag name,
  // except html and body elements
  var selector = $el.parents(':not(html,body)')
    .map(function() {
      var parentIndex = $(this).index();

      return this.tagName + _getChildSelector(parentIndex);
    })
    .get()
    .reverse()
    .join(' ');

  if (selector) {
    // get node name from the element itself
    selector += ' ' + $el[0].nodeName +
      // get child selector from element ifself
      _getChildSelector($el.index());
  }

  selector += _getIdAndClassNames($el);

  return selector;
}

jQuery 플러그인을 만드는 데 유용할까요?

클릭한 HTML 요소의 선택기 경로를 얻을 수 있습니다.

 $("*").on("click", function() {

    let selectorPath = $(this).parents().map(function () {return this.tagName;}).get().reverse().join("->");

    alert(selectorPath);

    return false;

});

간단한 jQuery 플러그인을 작성했습니다.

ID 또는 클래스 이름을 확인하고, 가능한 한 정확한 선택기를 지정합니다.

jQuery.fn.getSelector = function() {

    if ($(this).attr('id')) {
        return '#' + $(this).attr('id');
    }

    if ($(this).prop("tagName").toLowerCase() == 'body')    return 'body';

    var myOwn = $(this).attr('class');
    if (!myOwn) {
        myOwn = '>' + $(this).prop("tagName");
    } else {
        myOwn = '.' + myOwn.split(' ').join('.');
    }

    return $(this).parent().getSelector() + ' ' + myOwn;
}

클릭한 현재 태그의 이름을 가져오시겠습니까?

만약 그렇다면 이렇게 하세요.

$("*").click(function(){
    alert($(this)[0].nodeName);
});

"선택기"를 얻을 수는 없지만, 당신의 경우에 "선택기"는*.

자바스크립트 코드는 필요한 사람이 있을 경우 내가 필요로 하는 것과 같습니다.이것은 단지 위에서 선택한 답변의 번역일 뿐입니다.

    <script type="text/javascript">

function getAllParents(element){
    var a = element;
    var els = [];
    while (a && a.nodeName != "#document") {
        els.unshift(a.nodeName);
        a = a.parentNode;
    }
    return els.join(" ");
}

function getJquerySelector(element){

    var selector = getAllParents(element);
    /* if(selector){
        selector += " " + element.nodeName;
    } */
    var id = element.getAttribute("id");
    if(id){
        selector += "#" + id;
    }
    var classNames = element.getAttribute("class");
    if(classNames){
        selector += "." + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, ".");
    }
    console.log(selector);
    alert(selector);
    return selector;
}
</script>

고마워요 p1nox!

저의 문제는 양식의 일부를 수정하는 아약스 콜에 다시 초점을 맞추는 것이었습니다.

$.ajax({  url : "ajax_invite_load.php",
        async : true,
         type : 'POST',
         data : ...
     dataType : 'html',
      success : function(html, statut) {
                    var focus = $(document.activeElement).getSelector();
                    $td_left.html(html);
                    $(focus).focus();
                }
});

jQuery 플러그인에 당신의 기능을 캡슐화하고 싶었을 뿐입니다.

    !(function ($, undefined) {

    $.fn.getSelector = function () {
      if (!this || !this.length) {
        return ;
      }

      function _getChildSelector(index) {
        if (typeof index === 'undefined') {
          return '';
        }

        index = index + 1;
        return ':nth-child(' + index + ')';
      }

      function _getIdAndClassNames($el) {
        var selector = '';

        // attach id if exists
        var elId = $el.attr('id');
        if(elId){
          selector += '#' + elId;
        }

        // attach class names if exists
        var classNames = $el.attr('class');
        if(classNames){
          selector += '.' + classNames.replace(/^\s+|\s+$/g, '').replace(/\s/gi, '.');
        }

        return selector;
      }

      // get all parents siblings index and element's tag name,
      // except html and body elements
      var selector = this.parents(':not(html,body)')
        .map(function() {
          var parentIndex = $(this).index();

          return this.tagName + _getChildSelector(parentIndex);
        })
        .get()
        .reverse()
        .join(' ');

      if (selector) {
        // get node name from the element itself
        selector += ' ' + this[0].nodeName +
          // get child selector from element ifself
          _getChildSelector(this.index());
      }

      selector += _getIdAndClassNames(this);

      return selector;
    }

})(window.jQuery);

이름으로 요소 선택:

$('p').append('This is paragraph.'); // appends text to all p elements  
$('div').append('This is div.); 

<div>
    <p></p>
    <p></p>
</div>

ID로 요소 선택:

$('#impPrg').append('This element\'s id is "impPrg"');   
<p id="impPrg"></p>

이렇게 하면 DOM 경로가 표시되지 않지만 개체를 볼 때 크롬 디버거에서 볼 수 있는 문자열 표현이 출력됩니다.

$('.mybtn').click( function(event){
    console.log("%s", this);    // output: "button.mybtn"
});

https://developer.chrome.com/devtools/docs/console-api#consolelogobject-object

다음은 어떻습니까?

var selector = "*"
$(selector).click(function() {
    alert(selector);
});

저는 jQuery가 사용된 셀렉터 텍스트를 저장하고 있다고 생각하지 않습니다.결국, 당신이 이런 일을 한다면 그것이 어떻게 작용할까요?

$("div").find("a").click(function() {
    // what would expect the 'selector' to be here?
});

가장 좋은 대답은

var selector = '#something';

$(selector).anything(function(){
  console.log(selector);
});

언급URL : https://stackoverflow.com/questions/2420970/how-can-i-get-selector-from-jquery-object

반응형