返回节点文本(非递归) [英] Return node text (non-recursive)

查看:82
本文介绍了返回节点文本(非递归)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回一个表单元格的节点值。然而,方法text()会降低整个DOM树,并返回一个所有嵌套节点的字符串(表格单元格可能包含文本和html)。一旦我提取了节点的字符串,我想修改它并将其写回节点。修改后的文本由文本和HTML格式组成。



是否有任何可用于获取文本的jquery方法(或JavaScript)另一个可以用来写回文本的函数+ html(plain text()和html()在这种情况下不起作用,因为它们会覆盖子节点)?



干杯,
最大

解决方案

要从小孩文本节点获取文本,可以这样做:

  var text = $('selector')。contents()。map(function(){
//如果它是一个textNode,返回它的nodeValue
if(this.nodeType == 3)返回this.nodeValue;
})。get()。join('');

我不知道你想对文本做什么,但如果你想处理它随着你去,用新的文本/ HTML替换,你应该可以做一个 .each()而不是使用 .replaceWith()

$ b $每个(function(){
如果(this.nodeType == 3){$ b,则
pre $ p $ $ b //用文本
$(this).replaceWith('new processed value');
}
});

以下是一个示例: http://jsfiddle.net/ZNjCW/


I'd like to return a table cell's node value. The method text() however, goes down the whole DOM tree and returns a string of all nested nodes (the table cell may have text and html included). Once I have extracted the node's string, I'd like to modify it and write it back to the node. The modified text consists of text and html.

Is there any jquery method (or maybe Javascript) that can be used to get the text (without descending to the children) and another function that I can use to write back the text + html (plain text() and html() won't work in this case, as they would override the children nodes)?

Cheers, Max

解决方案

To get the text from child text nodes, you could do this:

var text = $('selector').contents().map(function() {
        // If it is a textNode, return its nodeValue
    if(this.nodeType == 3) return this.nodeValue;
}).get().join('');​​​​​​

I don't know exactly what you want to do with the text, but if you want to process it as you go and replace it with new text/html, you should be able to do an .each() instead and use .replaceWith().

$('selector').contents().each(function() {
    if(this.nodeType == 3) {
       // do something with the text
       $(this).replaceWith('new processed value');
    }
});​​​​​​

Here's an example: http://jsfiddle.net/ZNjCW/

这篇关于返回节点文本(非递归)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆