简体   繁体   English

如果某些没有标签的子节点,如何更改childNodes的innerHTML?

[英]How to change innerHTML of childNodes in case some childnodes without tags?

That is my example of problem 这是我的问题的例子

<div onclick="this.childNodes(0).innerHTML='0';">
1<b>2</b>3<b>4</b>5
</div>

as you see, two childnodes (" 2 " and " 4 ") are tagged, others are simple text. 如您所见,标记了两个子节点(“ 2 ”和“ 4 ”),其他是简单文本。 The question is how to change innerHTML of tagged and untagged nodes (texts) in sertain div container without touching other nodes/texts? 问题是如何在不接触其他节点/文本的情况下更改某个div容器中标记和未标记节点(文本)的innerHTML?

Essentially, you'll use the data (text) property for text nodes ( nodeType 3) and innerHTML otherwise ( fiddle ): 基本上,您将使用data (文本)属性用于文本节点( nodeType 3)和innerHTML否则( 小提琴 ):

<div onclick="this.childNodes[0][this.childNodes[0].nodeType === 3 ? 'data' : 'innerHTML'] = '0'">
1<b>2</b>3<b>4</b>5
</div>​

[edit] I'm getting really tired of everyone offering libraries as solutions when all that's required is a simple explanation of a basic concept, eg: text-nodes and element nodes have differing content properties, ie: data and innerHTML . [编辑]我真的厌倦了每个人都提供作为解决方案,而所需要的只是对基本概念的简单解释,例如:文本节点和元素节点具有不同的内容属性,即: datainnerHTML

I wrote a lib called Linguigi . 我写了一个名为Linguigi的lib。 It would be as easy as 这会很简单

new Linguigi(element).eachText(function(text) {
    if(this.parentNode.tagName === 'B') {
        return "BACON";
    }
});

which turns the text of all text nodes inside b-tags to "BACON". 它将b标签内所有文本节点的文本转换为“BACON”。 You get the original content as "text" parameter and could transform that. 您将原始内容作为“文本”参数获取并可以对其进行转换。

http://jsfiddle.net/Kz2jX/ http://jsfiddle.net/Kz2jX/

BTW: You should get rid of the inline event handling ( onclick attribute) 顺便说一句:你应该摆脱内联事件处理( onclick属性)

You can cycle through each of the nodes recursively, checking their nodeType property in turn and updating the nodeValue property with '0' if the node is a text node (indicated by nodeType == 3 ). 如果节点是文本节点(由nodeType == 3表示),则可以递归循环遍历每个节点,依次检查其nodeType属性并使用“0”更新nodeValue属性。

Assuming you have this HTML : 假设你有这个HTML

<div onclick="doReplace(this)">
    1<b>2</b>3<b>4</b>5
</div>

You can then write a simple replace function that calls itself recursively, like so: 然后,您可以编写一个简单的替换函数,以递归方式调用自身,如下所示:

window.doReplace = function (rootNode) {
    var children = rootNode.childNodes;
    for(var i = 0; i < children.length; i++) {
        var aChild = children[i];
        if(aChild.nodeType == 3) {
            aChild.nodeValue = '0';
        }
        else {
            doReplace(aChild);
        }
    }
}

A working fiddle can be found here: http://jsfiddle.net/p9YCn/1/ 可以在这里找到一个工作小提琴: http//jsfiddle.net/p9YCn/1/

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

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