获取选择器的元素路径 [英] Getting Element Path for selector
本文介绍了获取选择器的元素路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
遇到麻烦,基本上试图创建一个可以用作选择器的变量。例如
Running into a spot of trouble and basically trying to create a variable which can be used as a selector. eg
$('a').click(function(){
var selector = $(this).dompath();
});
HTML:
html
body
div
div /div
/div
ul
li
li
/ul
div
ul
li
li
li hello world
/ul
/div
body
html
然后会返回类似于
path = html body div ul li:contains('hello world')
然后我可以使用这个选择器来选择这个div,所以如果我喜欢
then i could use this in a selector to select this div so if i did like
$(path).text() would return "hello world"
非常感谢!
推荐答案
可能是这样的:
function dompath( element )
{
var path = '';
for ( ; element && element.nodeType == 1; element = element.parentNode )
{
var inner = $(element).children().length == 0 ? $(element).text() : '';
var eleSelector = element.tagName.toLowerCase() +
((inner.length > 0) ? ':contains(\'' + inner + '\')' : '');
path = ' ' + eleSelector + path;
}
return path;
}
这个修改了另一个问题要通过的方法,并将其全部添加通过:contains()
操作符的标签的文本内容,只有标签没有子标签。
This modified a method from another question to go through, and add in the full text contents of the tag via a :contains()
operator only if the tag has no children tags.
我已经使用这种方法进行了测试:
I had tested with this method:
$(document).ready(function(){
$('#p').click(function() {
console.log(dompath(this));
});
});
反对:
<html>
<body>
<div>
<div> </div>
</div>
<ul>
<li></li>
<li></li>
</ul>
<div>
<ul>
<li id="p">hi</li>
<li></li>
<li id="p2">hello world</li>
</ul>
</div>
<body>
<html>
点击p的结果然后输出为:
The results of clicking on p then get output as:
html body div ul li:contains('hi')
html body div ul li:contains('hi')
这篇关于获取选择器的元素路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文