并不完美,但写入速度快(你):)
http://jsfiddle.net/k1qs69fz/7/
代码:
function getCSSPath(el, callback){
var fullPath = '';
var cssPathFn = function (el, callback){
var elPath = '';
elPath = $(el).prop('tagName').toLowerCase();
if(typeof $(el).attr('id') !== 'undefined'){
elPath = elPath+'#'+$(el).attr('id');
}
if(typeof $(el).attr('class') !== 'undefined'){
elPath = elPath+'.'+$(el).attr('class').split(' ').join('.');
}
fullPath = elPath+' '+fullPath;
if(typeof $(el).parent().prop('tagName') !== 'undefined'){
cssPathFn($(el).parent(), callback);
}
else{
callback(fullPath);
}
};
cssPathFn(el, callback);
}
用法:
getCSSPath($('selector'), callbackFunction);
功能基于tag
名称,id
和class
名称,indexes
不受支持。
样品使用情况(HTML代码上的jsfiddle):
$(document).ready(function(){
getCSSPath($('#lorem-ipsum'), function (path){
console.log(path);
});
});
示例结果:
html body div#id1.c1.c2.c3 div#id2 div.c4.c5 span span.c6 ul li a span#lorem-ipsum
什么你想选择?请尝试提供更多信息。 – panther 2015-03-02 07:00:23
_“得到元素的唯一选择符”_ - 那里__is__没有这样的事情。元素可以以多种不同的方式进行选择。 – CBroe 2015-03-02 08:14:13
您是否正在寻找一个选择符*来唯一选择一个特定元素*,而不是一个*元素的唯一选择符*? – 2015-03-02 08:27:49