如何从jQuery对象中获取选择器

Fid*_*lip 106 javascript jquery jquery-selectors tree-traversal

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

有没有一种简单的方法来获得选择器$(this)?有一种方法可以通过选择器选择元素,但是从元素中获取选择器呢?

jes*_*vin 55

好的,所以在上面的评论中,提问者Fidilip说他/她真正想要的是获得当前元素的路径.

这是一个脚本,它将"攀爬"DOM祖先树,然后构建相当具体的选择器,包括单击项目上的任何idclass属性.

看到它在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>
Run Code Online (Sandbox Code Playgroud)

例如,如果您在下面的HTML中单击第二个列表嵌套列表项,您将得到以下结果:

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

  • 谢谢!我会在连接上使用你的代码进行一次修改......`join(">");`,会给我直接的孩子,因此更严格的*路径. (2认同)

Anu*_*rag 30

:: WARNING ::
.selector自版本1.7起已被弃用,自1.9起删除

jQuery对象有一个我在昨天挖掘代码时看到的选择器属性.不知道它在文档中的定义是否有多可靠(为了将来的证明).但它的确有效!

$('*').selector // returns *
Run Code Online (Sandbox Code Playgroud)

编辑:如果您要在事件中找到选择器,那么理想情况下该信息应该是事件本身的一部分而不是元素,因为元素可以通过各种选择器分配多个点击事件.一种解决方案是使用一个包装周围bind(),click()等等,而不是直接添加将它添加的事件.

jQuery.fn.addEvent = function(type, handler) {
    this.bind(type, {'selector': this.selector}, handler);
};
Run Code Online (Sandbox Code Playgroud)

选择器作为对象的属性名称传递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
});
Run Code Online (Sandbox Code Playgroud)

免责声明:请记住,就像使用live()事件一样,如果使用DOM遍历方法,则selector属性可能无效.

<div><a>a link</a></div>
Run Code Online (Sandbox Code Playgroud)

下面的代码将不起作用,因为live依赖于选择器属性,在这种情况下是a.parent()- 一个无效的选择器.

$('a').parent().live(function() { alert('something'); });
Run Code Online (Sandbox Code Playgroud)

我们的addEvent方法会触发,但你也会看到错误的选择器 - a.parent().

  • @Levitikon你是否真的低估了三年的答案,因为现在它被弃用了?!你应该确实编辑答案并发出警告 (12认同)

Wil*_*ill 21

与@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);
Run Code Online (Sandbox Code Playgroud)

缩小Javascript

// 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)
Run Code Online (Sandbox Code Playgroud)

用法和陷阱

<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>
Run Code Online (Sandbox Code Playgroud)

小提琴w/QUnit测试

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


小智 5

你试过这个吗?

 $("*").click(function(){
    $(this).attr("id"); 
 });
Run Code Online (Sandbox Code Playgroud)

  • 尽量不要使用`*`选择器,它很慢! (3认同)
  • 这仅在元素具有ID的情况下才有效。 (3认同)

jes*_*vin 0

您是否想获取当前单击的标签的名称?

如果是这样,请这样做..

$("*").click(function(){
    alert($(this)[0].nodeName);
});
Run Code Online (Sandbox Code Playgroud)

您无法真正获得“选择器”,您的情况下的“选择器”是*