如何通过单击一个html元素来获取xpath
我对编程相当陌生,必须在单击html元素时生成一个Xpath。
例如:如果我点击了用户名的文本框,那么它应该给我的xpath像
html / head / body / tr [1] / table [2] .....等等等。主要的是我不能使用萤火虫,因为我的应用程序彻底布莱恩在IE上运行。我已经看到很多fxn来获取xpath并试图整合它,但我没有得到返回值。一个简单的代码片段,其中我使用jquery click()函数来检索值是不工作的。事情是我无法在函数中传递html元素。我只从这个网站采取xpath函数。我的代码如下。
I am quite new to programming and have to generate a Xpath on clicking an html element. for example :if i have clicked on text box of username then it should give me the xpath like html/head/body/tr[1]/table[2]..... etc etc. The main thing is i can not use firebug as my application is thoroughly goin to run on IE. I have seen lot of fxn to get xpath and tried to integrate it but i am not getting the return value. A simple code snippet where i used jquery click() function to retrieve the value is not working.The thing is i am unable to pass the html element in the function.The xpath function i have taken from this site only. My code is below.
<!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;
}