如何遍历jQuery中的DOM对象? [英] How to traverse through DOM object in jQuery?
问题描述
我有这样的HTML.如何使用jQuery
遍历到<br>
标签?
I have HTML like this. How to traverse to <br>
tag using jQuery
?
条件:
- 不应使用类属性.
- 不应该使用拆分方法.
例如:
<html>
<body>
<div>
<div>
hello
</div>
123
<br>
paragraphs
<br>
escapes
<br>
</div>
</body>
</html>
对我来说,唯一的选择是使用<br>
标记遍历,
所以我该如何遍历<br>
并获取<br>
之后的下一个数据.
For me, only option is to traverse using <br>
tag,
so how can I loop through <br>
and get next data after <br>
.
我尝试像这样得到HTML
,但是无法循环使用<br>
.
I tried Like this getting the HTML
, but unable to loop through using <br>
.
var html=$(body).html();
我需要的输出:
逃脱"
Output I need:
"escapes"
您能帮我遍历<br>
标签吗?
推荐答案
您要查找的文本不在其自己的标记内.它们被称为文本节点,而jQuery没有简单的方法来获取它们.但是您可以在jquery中使用一些原始的JavaScript.
The texts you are seeking are not within their own tags. They are referred to as text-nodes, and jQuery doesn't have a simple way to grab them. But you can use a little raw JavaScript with your jquery to do so.
在此示例中,脚本捕获外部div内的所有文本节点(contents()
捕获每种类型的子节点,然后nodeType==3
上的filter
仅捕获文本节点),并循环遍历他们,提醒每个人:
In this example the script grabs all of the text-nodes inside the outer-div (contents()
grabs every type of child node, then filter
on nodeType==3
grabs just the text-nodes), and loops through them, alerting each:
$('body > div').contents().filter(function() {
return this.nodeType == 3;
})
.each(function(){
alert($(this).text());}
);
您将看到它在段落之前和最后一个换行符之后的外部div内找到空白(对于第一个和最后一个文本节点,警报为空),而且还找到了每个空格<br>
s
You'll see that it finds the white-spaces just inside the outer-div before the paragraph and after the last line-break (the alert is empty for the first and last text-nodes) but also finds each piece of text between the <br>
s
这篇关于如何遍历jQuery中的DOM对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!