gpt4 book ai didi

javascript - 如何通过单击 html 元素获取 xpath

转载 作者:太空狗 更新时间:2023-10-29 14:40:18 24 4
gpt4 key购买 nike

我是编程新手,必须在单击 html 元素时生成 Xpath。例如:如果我点击了用户名的文本框,那么它应该给我 xpath 之类的html/head/body/tr[1]/table[2]..... 等等。主要是我不能使用 firebug,因为我的应用程序完全可以在 IE 上运行。我已经看到很多 fxn 获取 xpath 并尝试集成它,但我没有得到返回值。我使用 jquery click() 函数检索值的简单代码片段不起作用。问题是我无法在函数中传递 html 元素。我仅从该站点获取的 xpath 函数。我的代码如下。

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>click demo</title>
<style>
p
{
color: red;
margin: 5px;
cursor: pointer;
}
p:hover
{
background: yellow;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js">
</script>
</head>
<body>
<p id ="test">First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<script>

$( "#test" ).click(function() { var value= $(this).getXPath();
alert(value) });

function getXPath( element )
{
var val=element.value;
alert("val="+val);
var xpath = '';
for ( ; element && element.nodeType == 1; element = element.parentNode )
{
alert(element);
var id = $(element.parentNode).children(element.tagName).index(element) + 1;
id > 1 ? (id = '[' + id + ']') : (id = '');
xpath = '/' + element.tagName.toLowerCase() + id + xpath;
}
return xpath;
}
</script>
</body>
</html>

最佳答案

将脚本更改为

$( "#test" ).click(function() { var value= getXPath( this  );
alert(value) });

function getXPath( element )
{
var val=element.value;
//alert("val="+val);
var xpath = '';
for ( ; element && element.nodeType == 1; element = element.parentNode )
{
//alert(element);
var id = $(element.parentNode).children(element.tagName).index(element) + 1;
id > 1 ? (id = '[' + id + ']') : (id = '');
xpath = '/' + element.tagName.toLowerCase() + id + xpath;
}
return xpath;
}

关于javascript - 如何通过单击 html 元素获取 xpath,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18606760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com