获取唯一的选择器jQuery [英] Get unique selector jQuery
问题描述
我需要能够为页面上的每个元素获得一个无选择的选择器.
I need to be able to get an unqiue selector for each element on a page.
例如,当我单击一个元素时,我想做这样的事情:
For example, when I click on an element I want to do something like this:
$(document).click(function(){
var sel = getUniqueSel(this);
});
因此,在将sel
值存储在数据库中之后,我可以获取该值并只需通过以下方式访问该元素
So, after storing the sel
value in a DB I can get that value and simply access the element by
var el = $(sel);
我无法更改并且对页面的HTML结构一无所知,并且我不能简单地向每个元素添加唯一ID(使用JS),因为这样效率低下.
I can't change and don't know anything about the HTML structure of the page and I can't simply add unique ID's (using JS) to every element as this would be inefficient.
推荐答案
另一种方法可能是在dom树上漫步并创建元素的路径,您可以将其保存并稍后再次用作选择器,尽管那样可能不是防弹的,但也许是您可以开始的地方.
Another approach might be to wander up the dom tree and create a path to the element, which you can save and use it later as a selector again, although that might not be bulletproof, but maybe its a point where you can start off.
使用注释中的建议更新了答案,现在返回ID(如果有)
只需访问 JSBin 上的示例,然后单击两次document
.
但请注意突出显示的内容.
Just visit the example on JSBin And click the document
twice.
but notice what gets highlighted..
jQuery.fn.getPath = function () {
if (this.length != 1) throw 'Requires one element.';
var path, node = this;
if (node[0].id) return "#" + node[0].id;
while (node.length) {
var realNode = node[0],
name = realNode.localName;
if (!name) break;
name = name.toLowerCase();
var parent = node.parent();
var siblings = parent.children(name);
if (siblings.length > 1) {
name += ':eq(' + siblings.index(realNode) + ')';
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
};
var sel;
$(document)
.click(function (e, a) {
if (!sel) {
sel = $("#comment-21702402")
.getPath();
alert("Path is: " + sel + ", hiding the Element -> Click again to highlight");
} else {
$(sel)
.css("background-color", "yellow");
}
});
这篇关于获取唯一的选择器jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!