Javascript 如何从 jQuery 对象获取选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2420970/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get selector from jQuery object
提问by Fidilip
$("*").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?
有没有一种简单的方法可以从中获取选择器$(this)?有一种方法可以通过它的选择器来选择一个元素,但是如何从 element 中获取选择器呢?
回答by jessegavin
Ok, so in a comment above the question asker Fidilipsaid that what he/she's really after is to get the path to the current element.
好的,所以在问题提问者上方的评论中,Fidilip他/她真正想要的是获取当前元素的路径。
Here's a script that will "climb" the DOM ancestor tree and then build fairly specific selector including any idor classattributes on the item clicked.
这是一个脚本,它将“爬升”DOM 祖先树,然后构建相当具体的选择器,包括单击的项目上的任何id或class属性。
See it working on jsFiddle: http://jsfiddle.net/Jkj2n/209/
看看它在 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 中的第二个列表嵌套列表项,您将获得以下结果:
HTML>BODY>UL>LI>UL>LI#sub2.subitem.otherclass
HTML>BODY>UL>LI>UL>LI#sub2.subitem.otherclass
回答by Anurag
::WARNING::
.selector has been deprecated as of version 1.7, removed as of 1.9
::WARNING::
.selector 已从 1.7 版开始弃用,从 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!
jQuery 对象有一个选择器属性,我昨天在挖掘它的代码时看到了它。不知道文档中是否定义了它的可靠性(以备将来证明)。但它有效!
$('*').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.
编辑:如果您要在事件中找到选择器,那么理想情况下该信息应该是事件本身而不是元素的一部分,因为一个元素可以通过各种选择器分配多个单击事件。一种解决方案是使用一个包装周围bind(),click()等等,而不是直接添加将它添加的事件。
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.
选择器作为对象的名为 的属性传递selector。作为event.data.selector.
Let's try it on some markup (http://jsfiddle.net/DFh7z/):
让我们在一些标记上尝试一下(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.
免责声明:请记住,就像live()事件一样,如果使用 DOM 遍历方法,选择器属性可能无效。
<div><a>a link</a></div>
The code below will NOT work, as liverelies on the selector property
which in this case is a.parent()- an invalid selector.
下面的代码将不起作用,因为它live依赖于选择器属性,在这种情况下是a.parent()- 一个无效的选择器。
$('a').parent().live(function() { alert('something'); });
Our addEventmethod will fire, but you too will see the wrong selector - a.parent().
我们的addEvent方法会触发,但您也会看到错误的选择器 - a.parent()。
回答by Will
In collaboration with @drzaus we've come up with the following jQuery plugin.
我们与@drzaus 合作开发了以下 jQuery 插件。
jQuery.getSelector
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
缩小的 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
小提琴与 QUnit 测试
回答by abhilashv
Did you try this ?
你试过这个吗?
$("*").click(function(){
$(this).attr("id");
});
回答by ngs
I've released a jQuery plugin: jQuery Selectorator, you can get selector like this.
我发布了一个 jQuery 插件:jQuery Selectorator,你可以得到这样的选择器。
$("*").on("click", function(){
alert($(this).getSelector().join("\n"));
return false;
});
回答by AmazingDayToday
Try this:
尝试这个:
$("*").click(function(event){
console.log($(event.handleObj.selector));
});
回答by Albert Horta
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 并且即使在较新的 jQuery 版本上也会返回“a”。回答by Vivek Kumar
This can get you selector path of clicked HTML element-
这可以为您提供单击的 HTML 元素的选择器路径 -
$("*").on("click", function() {
let selectorPath = $(this).parents().map(function () {return this.tagName;}).get().reverse().join("->");
alert(selectorPath);
return false;
});
回答by Codemole
Well, I wrote this simple jQuery plugin.
好吧,我写了这个简单的 jQuery 插件。
This checkes id or class name, and try to give as much exact selector as possible.
这会检查 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;
}
回答by Azghanvi
I was getting multiple elements even after above solutions, so i extended dds1024 work, for even more pin-pointing dom element.
即使在上述解决方案之后,我也得到了多个元素,所以我扩展了 dds1024 工作,以获得更多精确的 dom 元素。
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)
例如 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;
}

