我试图在html dom中获取特定对象的路径.
使用javascript或jquery.(当我选择/悬停在对象上时.)
我事先不知道结构.
例如:
<html>
<body>
<div>
<div>
Not selected
</div>
<div>
Selected Text
</div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
"选定文本"Div路径应该类似于:
//HTML/BODY/DIV[0]/DIV[1]
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激.
我已经看过这个答案,但它没有给出关于元素索引的指示(在我的例子中,方括号中的值为1 DIV[1]).
顺便说一下,这条路有"技术"名称吗?
我看过XPath这个术语,但不确定是不是这样.
快乐,享受生活.
Fré*_*idi 17
以下函数使用jQuery执行您想要的操作:
function getElementPath(element)
{
return "//" + $(element).parents().andSelf().map(function() {
var $this = $(this);
var tagName = this.nodeName;
if ($this.siblings(tagName).length > 0) {
tagName += "[" + $this.prevAll(tagName).length + "]";
}
return tagName;
}).get().join("/").toUpperCase();
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它:
$(document).ready(function() {
$("div").click(function(event) {
event.stopPropagation();
window.alert(getElementPath(this));
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7832 次 |
| 最近记录: |