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

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

4

19 回答 19

59

好的,所以在提问者上方的评论中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

于 2010-03-10T23:10:30.960 回答
35

::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 遍历方法,则选择器属性可能无效。

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

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

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

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

于 2010-03-10T22:36:20.470 回答
22

通过与@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);

缩小的 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)

使用和陷阱

<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/

于 2013-03-25T19:42:43.660 回答
5

你试过这个吗?

 $("*").click(function(){
    $(this).attr("id"); 
 });
于 2012-12-04T11:11:25.903 回答
3

尝试这个:

$("*").click(function(event){
    console.log($(event.handleObj.selector));
 });
于 2016-02-10T20:12:52.693 回答
2

我发布了一个 jQuery 插件:jQuery Selectorator,你可以像这样得到选择器。

$("*").on("click", function(){
  alert($(this).getSelector().join("\n"));
  return false;
});
于 2013-08-10T02:25:50.967 回答
2

只需以这种方式在 $ 函数上添加一个层:

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

现在你可以做类似的事情

$("a").selector
即使在较新的 jQuery 版本上也会返回“a”。

于 2017-10-20T08:24:13.483 回答
2

好吧,我写了这个简单的 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;
}
于 2017-07-29T15:40:15.250 回答
1

我为@jessegavin 的修复添加了一些修复。

如果元素上有 ID,这将立即返回。我还添加了一个名称属性检查和一个 nth-child 选择器,以防元素没有 id、类或名称。

如果页面上有多个表单并且有类似的输入,则该名称可能需要范围,但我还没有处理。

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;
}
于 2012-12-30T18:35:16.233 回答
1

http://www.selectorgadget.com/是专门为此用例设计的书签。

也就是说,我同意大多数其他人的观点,即你应该自己学习 CSS 选择器,试图用代码生成它们是不可持续的。:)

于 2011-10-12T01:19:39.233 回答
1

考虑到此处阅读的一些答案,我想提出以下建议:

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 插件有用?

于 2016-01-28T20:12:44.567 回答
1

即使在上述解决方案之后,我也得到了多个元素,所以我扩展了 dds1024 的工作,以获得更多精确的 dom 元素。

例如 DIV:nth-child(1) DIV:nth-child(3) DIV:nth-child(1) ARTICLE: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;
}
于 2015-12-28T01:57:42.303 回答
1

这可以让您获得单击的 HTML 元素的选择器路径-

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

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

    alert(selectorPath);

    return false;

});
于 2017-01-25T13:20:20.987 回答
0

您是否试图获取被点击的当前标签的名称?

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

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

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

于 2010-03-10T22:08:29.343 回答
0

相同的 Javascript 代码,以防任何人需要,因为我需要它。这只是上述选定答案的翻译。

    <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>
于 2013-05-05T06:11:03.147 回答
0

谢谢p1nox!

我的问题是将焦点重新放在修改表单的一部分的 ajax 调用上。

$.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);
于 2019-05-29T14:45:51.603 回答
-1

这不会向您显示 DOM 路径,但会在查看对象时输出您在例如 chrome 调试器中看到的内容的字符串表示形式。

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

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

于 2016-04-11T13:17:48.247 回答
-4

怎么样:

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

我不相信 jQuery 存储使用的选择器文本。毕竟,如果您执行以下操作,那将如何工作:

$("div").find("a").click(function() {
    // what would expect the 'selector' to be here?
});
于 2010-03-10T22:08:43.433 回答
-8

最好的答案是

var selector = '#something';

$(selector).anything(function(){
  console.log(selector);
});
于 2018-01-10T08:42:46.880 回答