如何从 jQuery 对象获取选择器

发布于 2024-08-24 06:27:45 字数 222 浏览 4 评论 0原文

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

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

$("*").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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(21

岛徒 2024-08-31 06:27:46

我们与@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>

Fiddle w/ QUnit 测试

http://jsfiddle.net/CALY5/5/< /a>

In collaboration with @drzaus we've come up with the following jQuery plugin.

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

Minified 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)

Usage and 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>

Fiddle w/ QUnit tests

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

书间行客 2024-08-31 06:27:46

你尝试过这个吗?

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

Did you try this ?

 $("*").click(function(){
    $(this).attr("id"); 
 });
白芷 2024-08-31 06:27:46

只需在 $ 函数上添加一个层,如下所示:

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

现在你可以做类似的事情

$("a").selector

and will return "a" even on newer jQuery versions.

Just add a layer over the $ function this way:

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

Now you can do things like

$("a").selector

and will return "a" even on newer jQuery versions.

掩于岁月 2024-08-31 06:27:46

试试这个:

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

Try this:

$("*").click(function(event){
    console.log($(event.handleObj.selector));
 });
白衬杉格子梦 2024-08-31 06:27:46

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

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

http://www.selectorgadget.com/ is a bookmarklet designed explicitly for this use case.

That said, I agree with most other people in that you should just learn CSS selectors yourself, trying to generate them with code is not sustainable. :)

_畞蕅 2024-08-31 06:27:46

我在@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;
}

I added some fixes to @jessegavin's fix.

This will return right away if there is an ID on the element. I also added a name attribute check and a nth-child selector in case a element has no id, class, or name.

The name might need scoping in case there a multiple forms on the page and have similar inputs, but I didn't handle that yet.

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;
}
蓝色星空 2024-08-31 06:27:46

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

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

I've released a jQuery plugin: jQuery Selectorator, you can get selector like this.

$("*").on("click", function(){
  alert($(this).getSelector().join("\n"));
  return false;
});
ぃ双果 2024-08-31 06:27:46

即使在上述解决方案之后,我仍然获得了多个元素,因此我扩展了 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;
}

I was getting multiple elements even after above solutions, so i extended dds1024 work, for even more pin-pointing dom element.

e.g. 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)

Code:

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;
}
玻璃人 2024-08-31 06:27:46

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

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

Taking in account some answers read here I'd like to propose this:

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

Maybe useful to create a jQuery plugin?

云裳 2024-08-31 06:27:46

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

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

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

    alert(selectorPath);

    return false;

});

This can get you selector path of clicked HTML element-

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

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

    alert(selectorPath);

    return false;

});
伊面 2024-08-31 06:27:46

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

Well, I wrote this simple jQuery plugin.

This checkes id or class name, and try to give as much exact selector as possible.

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;
}
り繁华旳梦境 2024-08-31 06:27:46

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

如果是这样,请执行此操作..

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

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

Are you trying to get the name of the current tag that was clicked?

If so, do this..

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

You can't really get the "selector", the "selector" in your case is *.

枕梦 2024-08-31 06:27:46

相同的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>

Javascript code for the same, in case any one needs, as i needed it. This just the translation only of the above selected answer.

    <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>
貪欢 2024-08-31 06:27:46

谢谢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);

Thank you p1nox!

My problem was to put focus back on an ajax call that was modifying part of the form.

$.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();
                }
});

I just needed to encapsulate your function in a jQuery plugin:

    !(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);
酒绊 2024-08-31 06:27:46

按名称选择元素:

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

Select Elements by Name :

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

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

Select Elements by Id:

$('#impPrg').append('This element\'s id is "impPrg"');   
<p id="impPrg"></p>
怀里藏娇 2024-08-31 06:27:46

几乎完美,除了:如果您使用文本作为参数,则不需要此片段,因为您已经知道了。但是..如果您使用对象作为参数,您想知道原始参数。所以再多一点代码。如果是这种情况,则选择器已经由先前的函数设置,因此您所要做的就是获取选择器的选择器! (嗯?)。您只是不能使用 null 值,因为那也是一个对象。让我们来看看:

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

为了使其完整,您还可以使用第二个参数中的上下文并将其放在选择器前面:

$ = (function(jQ) { 
    return (function() { 
        var fnc = jQ.apply(this,arguments);
        fnc.selector = (arguments.length>0)?arguments[0]:undefined;
        fnc.context = (arguments.length>1)?arguments[1]:undefined;
        if (typeof fnc.selector === "object") {
            fnc.context = fnc.selector.context;
            fnc.selector = fnc.selector.selector;
        }
        if (fnc.context !== undefined) {
            fnc.selector = fnc.context + " " + fnc.selector;
        }
        if (fnc.selector === undefined) {
            delete fnc.selector;
        }
        delete fnc.context;
        return fnc; 
    });
})($);

然而...该代码破坏了所有 jQuery 函数。
原因:新的 jQuery 对象替换了原来的 $ 对象。

与此同时,我发现了一种新方法,即扩展 jQuery。

$.fn.extend({
    initConstructor: $.fn.init,
    init: function (selector, context, rootjQuery) {
        var obj = new $.fn.initConstructor(selector, context, rootjQuery);
        if (selector !== undefined) {
            obj.selector = selector;
            if (obj.selector.selector !== undefined) {
                obj.selector = obj.selector.selector;
            }
        }
        return obj;
    }
});

该代码可以在就绪上下文内部也可以在外部使用。您还可以为上下文参数扩展此代码。

Almost perfect, except: If you used text as an argument, you don't need this snippet, because you already know. But.. if you used an object as an argument, you want to know the original argument. So a little more code. If this is the case, the selector is already set by a previous function, so all you have to do is get the selector of the selector!!! (huh?). You only can't use the null value, because that is an object too. Let's see:

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

To make it complete, you can also use the context from the second argument and put it in front of the selector:

$ = (function(jQ) { 
    return (function() { 
        var fnc = jQ.apply(this,arguments);
        fnc.selector = (arguments.length>0)?arguments[0]:undefined;
        fnc.context = (arguments.length>1)?arguments[1]:undefined;
        if (typeof fnc.selector === "object") {
            fnc.context = fnc.selector.context;
            fnc.selector = fnc.selector.selector;
        }
        if (fnc.context !== undefined) {
            fnc.selector = fnc.context + " " + fnc.selector;
        }
        if (fnc.selector === undefined) {
            delete fnc.selector;
        }
        delete fnc.context;
        return fnc; 
    });
})($);

However... the code destroys all jQuery functions.
Reason: a new jQuery object replaces the original $ object.

In the meantime I dicovered a new way, by extending jQuery.

$.fn.extend({
    initConstructor: $.fn.init,
    init: function (selector, context, rootjQuery) {
        var obj = new $.fn.initConstructor(selector, context, rootjQuery);
        if (selector !== undefined) {
            obj.selector = selector;
            if (obj.selector.selector !== undefined) {
                obj.selector = obj.selector.selector;
            }
        }
        return obj;
    }
});

This code can be used inside as well outside the ready context. Also you can expand this code for the context argument.

戒ㄋ 2024-08-31 06:27:46

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

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

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

This won't show you the DOM path, but it will output a string representation of what you see in eg chrome debugger, when viewing an object.

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

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

心作怪 2024-08-31 06:27:46

怎么样:

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

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

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

How about:

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

I don't believe jQuery store the selector text that was used. After all, how would that work if you did something like this:

$("div").find("a").click(function() {
    // what would expect the 'selector' to be here?
});
暖风昔人 2024-08-31 06:27:46

最好的答案是

var selector = '#something';

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

The best answer would be

var selector = '#something';

$(selector).anything(function(){
  console.log(selector);
});
我做我的改变 2024-08-31 06:27:45

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

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

查看它在 jsFiddle 上的工作情况:http://jsfiddle.net/Jkj2n/209/< /strong>

<!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< /代码>

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.

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.

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>

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

北方。的韩爷 2024-08-31 06:27:45

::警告::
.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
});

免责声明< /strong>:请记住,就像 live() 事件一样,如果使用 DOM 遍历方法,选择器属性可能无效。

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

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

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

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

::WARNING::
.selector has been deprecated as of version 1.7, removed as of 1.9

The jQuery object has a selector property I saw when digging in its code yesterday. Don't know if it's defined in the docs are how reliable it is (for future proofing). But it works!

$('*').selector // returns *

Edit: If you were to find the selector inside the event, that information should ideally be part of the event itself and not the element because an element could have multiple click events assigned through various selectors. A solution would be to use a wrapper to around bind(), click() etc. to add events instead of adding it directly.

jQuery.fn.addEvent = function(type, handler) {
    this.bind(type, {'selector': this.selector}, handler);
};

The selector is being passed as an object's property named selector. Access it as event.data.selector.

Let's try it on some markup (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
});

Disclaimer: Remember that just as with live() events, the selector property may be invalid if DOM traversal methods are used.

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

The code below will NOT work, as live relies on the selector property
which in this case is a.parent() - an invalid selector.

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

Our addEvent method will fire, but you too will see the wrong selector - a.parent().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文