功能如下:
1
2
3
4
如果传入id="span_3"的元素,生成的xpath是body>ul[0]>li[0]>span[2]实现如下文js代码,需引入jqueryfunction getPath($ele) {
function path(el, obj) {
if (el[0].nodeName === 'BODY') {
obj['BODY'] = ''
return obj
} else if (el.parent()[0].nodeName === 'BODY') {
var children = el.parent().children()
for (var i = 0, len = children.length; i < len; i++) {
if (el[0] === children[i]) {
obj[el[0].nodeName] = i
}
}
obj['BODY'] = ''
return obj
} else {
var children = el.parent().children()
for (var i = 0, len = children.length; i < len; i++) {
if (el[0] === children[i]) {
obj[el[0].nodeName] = i
}
}
path(el.parent(), obj)
}
}
let o = {};
path($ele, o)
var str = ''
for (var k in o) {
if (o[k] === '') {
str += k + "&"
} else {
str += k + "[" + o[k] + "]" + "&"
}
}
return str.trim().split("&").reverse().join(">").slice(1).toLowerCase()
}
// 使用
console.log(getPath($('#test')))