如何从jQuery对象中获取选择器 [英] How can I get selector from jQuery object

查看:122
本文介绍了如何从jQuery对象中获取选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

是否可以通过 $获取选择器的简单方法(这个) ?有一种方法可以通过选择器选择元素,但从元素获取选择器怎么样?

Is there an easy way to get selector from $(this)? There is a way to select an element by its selector, but what about getting the selector from element?

推荐答案

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

Ok, so in a comment above the question asker Fidilip said that what he/she's really after is to get the path to the current element.

这是一个脚本,它将攀爬DOM祖先树,然后构建相当具体的选择器,包括任何 id class 属性。

Here's a script that will "climb" the DOM ancestor tree and then build fairly specific selector including any id or class attributes on the item clicked.

查看jsFiddle上的工作: http://jsfiddle.net/Jkj2n/209/

See it working on 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中的第二个列表嵌套列表项,你会得到以下结果:

For example, if you were to click the 2nd list nested list item in the HTML below, you would get the following result:

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

这篇关于如何从jQuery对象中获取选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆