本文介绍了将xPath转换为jQuery选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将以下xPath转换为jQuery 1.10选择器?
How do I convert the following xPath into a jQuery 1.10 selector?
/html/body/div[4]/div[2]/div/div/div/ul/li[4]
我想用结果来做这样的事情:
I'd like to use the result to do something like this:
jQuery('selector').hide();
推荐答案
嗯,这是识别语法差异的问题:
Well, it's a question of identifying the syntactical differences:
- XPath使用
/
作为父/子定界符,而CSS/jQuery选择器使用>
. - XPath使用一个索引的方括号表示索引,而jQuery使用
:nth-child()
伪选择器
- XPath uses
/
as a parent/child delimiter, while CSS/jQuery selectors use>
. - XPath uses one-indexed square brackets to denote index, whereas jQuery uses the
:nth-child()
pseudo-selector
所以:
var
xpath = '/html/body/div[4]/div[2]/div/div/div/ul/li[4]',
jq_sel = xpath
.substr(1) //discard first slash
.replace(/\//g, ' > ')
.replace(/\[(\d+)\]/g, function($0, i) { return ':nth-child('+i+')'; });
这篇关于将xPath转换为jQuery选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!