我有一些没有标签的文字.我试着找到它.用jQuery
(这是dinamic文本,所以我不知道我有多少文本的和平或它们在哪里.我只知道它们在div中.这与其他问题不同)
我可以找到一个解决方案,找到没有标签的文本,将其包装<p>
但是这也会生成一些空的p标签.所以问题是:
- This.nodeType === 3似乎找到了文本和空格.谁能解释一下?
- 有人可以解决此问题或显示另一种方法来只查找没有标签的文本吗?
(我可以找到nodeType === 3"表示元素或属性中的文本内容")
如果你喜欢在那里玩,请小提琴:http://jsfiddle.net/bhpaf8hu/
$("#tot").click(function() {
$("div").contents().filter(function() {
return this.nodeType === 3;
}).wrap("<p>");
});
Run Code Online (Sandbox Code Playgroud)
p { background:green; }
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="tot">
<h1> This is a h1</h1>
Text without p
<br>
Another text without p
<br>
<p>This text has p</p>
</div>
Run Code Online (Sandbox Code Playgroud)
解决方案预期:所以我想找到没有标签的文本并将其包装在ap标签中.在这个例子中,这就是我要寻找的:
<div id="tot">
<h1> This is a h1</h1>
<p>Text without p</p>
<br>
<p>Another text without p</p>
<br>
<p>This text has p</p>
</div>
Run Code Online (Sandbox Code Playgroud)
避免包裹和空白空间的一种解决方案是使用如下修剪:
$("#tot")
.contents()
.filter(function () {
// get only the text nodes
return this.nodeType === 3 && this.nodeValue.trim() !== "";
}).wrap("<p />");
Run Code Online (Sandbox Code Playgroud)
参考
归档时间: |
|
查看次数: |
373 次 |
最近记录: |