我对编程很陌生,必须在单击 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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)