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

时间:2010-03-10 22:04:06

标签: javascript jquery jquery-selectors tree-traversal

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

$(this) 获取选择器是否容易?有一种方法可以通过选择器选择一个元素,但从元素中获取选择器怎么样?

18 个答案:

答案 0 :(得分: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>

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

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

答案 1 :(得分:28)

:: 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依赖于selector属性 在这种情况下,a.parent()是一个无效的选择器。

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

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

答案 2 :(得分: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);

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

小提琴w / QUnit测试

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

答案 3 :(得分:5)

你尝试过这个吗?

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

答案 4 :(得分:2)

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

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

答案 5 :(得分:2)

试试这个:

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

答案 6 :(得分:1)

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

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

答案 7 :(得分:1)

我在@ jessegavin修复中添加了一些修复。

如果元素上有ID,则会立即返回。我还添加了名称属性检查和第n个子选择器,以防元素没有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;
}

答案 8 :(得分:1)

只需在$ function上添加一个图层:

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

现在您可以执行

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

答案 9 :(得分:1)

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

e.g。 DIV:n-child(1)DIV:n-child(3)DIV:n-child(1)文章:n-child(1)DIV:n-child(1)DIV:n-child(8)DIV: nth-child(2)DIV:n-child(1)DIV:n-child(2)DIV:n-child(1)H4:n-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;
}

答案 10 :(得分:1)

好吧,我写了这个简单的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;
}

答案 11 :(得分:1)

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

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

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

    alert(selectorPath);

    return false;

});

答案 12 :(得分: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);

答案 13 :(得分:0)

您是否尝试获取所点击的当前代码的名称?

如果是,请这样做..

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

你无法真正获得“选择器”,你的案例中的“选择器”是*

答案 14 :(得分:0)

考虑到这里读到的一些答案,我想提出这个问题:

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

答案 15 :(得分: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>

答案 16 :(得分:-3)

怎么样:

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

我不相信jQuery存储使用的选择器文本。毕竟,如果你做了这样的事情,那将是如何工作的:

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

答案 17 :(得分:-4)

最好的答案是

var selector = '#something';

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