Ita*_*vka 32 javascript jquery jquery-selectors textnode
使用jQuery.我有以下html:
<input type="checkbox" name='something' value='v1' /> All the world <br />
Run Code Online (Sandbox Code Playgroud)
我怎么才能获得文本.我应该使用什么选择器?(我需要"全世界")
我也无法触摸HTML ...
Sel*_*gam 55
尝试使用DOM函数 .nextSibling选择下一个节点(包括文本节点)并使用它nodeValue来获取文本All the world
$(':checkbox')[0].nextSibling.nodeValue
Run Code Online (Sandbox Code Playgroud)
只需使用plain-JavaScript nextSibling,尽管你必须"退出"jQuery才能使用该方法(因此[0]):
var text = $('input:checkbox[name="something"]')[0].nextSibling.nodeValue;
Run Code Online (Sandbox Code Playgroud)
我终于意识到我的其他建议有什么问题,这个建议已经修复:
var text = $('input:checkbox[name="something"]').parent().contents().filter(
function(){
return this.nodeType === 3 && this.nodeValue.trim() !== '';
}).first().text();
Run Code Online (Sandbox Code Playgroud)
而要确保你只得到了textNodes从之前的br(虽然坦言这是变得过于复杂,并且第一建议更容易的工作,而且我怀疑可靠):
var text = $('input:checkbox[name="something"]').parent().contents().filter(
function(){
return this.nodeType === 3 && this.nodeValue.trim() !== '' && $(this).prevAll('br').length === 0;
}).text();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21120 次 |
| 最近记录: |