随便改了个name,可以看到输出结果:#document>html>body>div>label
[HTML] 纯文本查看 复制代码 <!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="jquery-3.4.1.js"></script>
<script>
jQuery.fn.getPath = function () {
if (this.length != 1) throw 'Requires one element.';
var path, node = this;
while (node.length) {
var realNode = node[0], name = realNode.nodeName;
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;
};
</script>
</head>
<body>
<div>
<label id="test"></label>
</div>
<script>
var p = $('#test').getPath();
console.log(p);
</script>
</body>
</html> |