你可以使用这个函数,它基本上需要一个元素并向后工作以查看它的确切路径。我没有将它用于您的计划,但我不明白为什么它不起作用。
function mirrorpath ( elm ) {
/// add an indentifying segment to the path for each parent element
var addtopath = function( elm ){
var node = $(elm), ident = '';
/// first off, add our nodeName to our identity
ident += node.get(0).nodeName;
/// if we have an id, then we are specific enough
if ( node.attr('id') ) {
ident += '#' + node.attr('id');
}
/// otherwise
else{
/// if we have a class, that's good :)
if ( node.attr('class') ) {
ident += '.' + node.attr('class').split(' ').join('.');
}
/// now make it more accurate with an index offset
ident += ':eq('+node.prevAll(ident).add(node).index(node)+')';
}
/// add our new path segment
path.push( ident );
}
/// step through the target elements parents and build our path
var parents = $(elm).parents().get(), path = [], i = parents.length;
while ( i-- ) { addtopath( parents[i] ); }; addtopath( elm );
/// implode the path and return
return path.join(' ');
}
返回的路径应该评估并在主页和 iframe 上找到您的元素 - 您所要做的就是将路径反馈回 jQuery。我不得不承认你的问题是一个相当奇怪的要求;)
附言。我没有在非常复杂的深度元素中测试过这段代码,所以在某些情况下它可能会失败......它也可以通过不使用数组进行路径存储来优化(并愚蠢地在每次迭代中重新加入...... 我刚刚更新了代码以优化这个问题)但是感谢 jQuery 和 Sizzle,它适用于我迄今为止所需要的一切。
编辑/更新
以防万一这很有用,我决定为自己修改一下代码并将其转换为 jQuery 插件。现在有一些关于实际 css 路径的生成的优化,以及当 jQuery 解析路径时的优化。
(function($){
$.fn.cssPath = function () {
var paths = [], addtopath = function( elm ){
if ( elm && (elm.nodeName || (elm instanceof $ && elm.length)) ) {
var node = $(elm), ident = String(node.get(0).nodeName).toLowerCase();
/// if we have an id, then we are specific enough
if ( node.attr('id') ) {
ident += '#' + node.attr('id');
}
/// otherwise
else{
/// if we have a class, that's good :)
if ( node.attr('class') ) {
ident += '.' + node.attr('class').split(' ').join('.');
};
/// make sure there is a point to being more specific (leads to nicer paths)
if ( node.siblings(ident).length > 0 ) {
/// now make it more accurate with an index offset
//ident += ':eq('+node.prevAll(ident).add(node).index(node)+')';
ident += ':nth-child('+(node.index()+1)+')';
};
};
/// add our new path segment
return ident;
};
};
this.each(function(){
/// find the parents for this element, and add the current element to the list
var parents = $(this).parents().get(), path = '', i = parents.unshift(this) && parents.length;
/// build up the path string per parent
while ( i-- ) { path += (path ? ' > ' : '') + addtopath( parents[i] ); };
/// return the path to our paths list
paths.push(path);
});
/// if one path, return string, if more return array
return ( paths.length > 1 ? paths : paths[0] );
}
})((typeof jQuery != undefined) && jQuery);
用法:
var path = $('#my_target_element').cssPath();
示例输出:
html > body > div#BlogArchive1 > ul.hierarchy > li.archivedate.expanded > a