简体   繁体   English

返回节点文本(非递归)

[英]Return node text (non-recursive)

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). 然而,方法text()沿着整个DOM树向下并返回所有嵌套节点的字符串(表格单元格可能包含text和html)。 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. 修改后的文本由文本和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)? 是否有任何jquery方法(或者可能是Javascript)可用于获取文本(不会降级到子级)和另一个我可以用来写回文本的函数+ html(纯文本()和html()赢了'在这种情况下工作,因为他们会覆盖子节点)?

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() . 我不知道你想要对文本做什么,但是如果你想要处理它并用新的text / html替换它,你应该能够做一个.each()而是使用.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/ 这是一个例子: http //jsfiddle.net/ZNjCW/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM