简体   繁体   English

在包含其他标记的标记中将一个文本替换为另一个文本

[英]Replace one text with another in a tag containing other tags

I have the following HTML element: 我有以下HTML元素:

<p id="myP">Some text<span onclick="myFunc()"> to change</span></p>

My idea is to replace "Some text" with "Some other text" when someone clicks on the "to change" span. 我的想法是当有人点击“更改”范围时,将“某些文字”替换为“其他文字”。 So my first try was: 所以我的第一次尝试是:

function myFunc(){
    var myP = document.getElementById("myP");
    myP.innerText = "Some other text";
}

... However, I have already learned from my mistakes that this would over-ride not only the text, but also the span element nested in the p. ...但是,我已经从我的错误中了解到,这不仅会覆盖文本,还会覆盖嵌套在p中的span元素。 So, using the learning of the last time, I've tried to rather create a text node: 所以,使用上一次的学习,我试图创建一个文本节点:

function myFunc(){
    var myP = document.getElementById("myP");
    myP.appendChild(document.createTextNode("Some other text"));
} 

However this is clearly wrong, because it would append the text and not replace it. 然而,这显然是错误的,因为它会附加文本而不是替换它。 How should I write my JavaScript function to obtain the pure replacement of Some text with Some other text , without however affecting the nested span? 我应该如何编写我的JavaScript函数来获取某些文本的纯替换以及其他一些文本 ,而不会影响嵌套范围?

I know this might seem a basic question, but I'm a complete beginner and don't know how well yet how to treat with HTML objects. 我知道这似乎是一个基本问题,但我是一个完全的初学者,并不知道如何处理HTML对象。 Thanks in advance 提前致谢

NOTE I think that I could do simply this: 注意我认为我可以做到这一点:

myP.innerText = "Some other text<span onclick="myFunc()"> to change</span>"

... but apart for being complicated because this is a minimized example wrt the real code, I imagine it's the most unelegant solution ever, so I would like to learn the proper way. ...但除了复杂之外,因为这是真实代码的最小化示例,我认为它是有史以来最不优雅的解决方案,所以我想学习正确的方法。

Just get the textNode 只需获取textNode

 function myFunc(){ var myP = document.getElementById("myP").firstChild; myP.nodeValue = "Some other text"; } 
 <p id="myP">Some text<span onclick="myFunc()"> to change</span></p> 

Why not just implement it using another element? 为什么不用另一个元素来实现呢?

<p><span id="to-change">Some text</span> <span onclick="myFunc()">to change</span></p>
function myFunc(){
    document.getElementById("to-change").innerText = "Some other text";
}

Or you can replace the first text node with a new one: 或者您可以用新的节点替换第一个文本节点:

 function myFunc() { var myP = document.getElementById("myP"); myP.replaceChild(document.createTextNode("Some other text"), myP.childNodes[0]); } 
 <p id="myP">Some text<span onclick="myFunc()"> to change</span></p> 

For the really simple approach: 对于非常简单的方法:

 function myFunc(){ var myP = document.getElementById("myP"); var cn = myP.childNodes[0]; // where cn.nodeType == 3 (text node) cn.textContent = "Some other text"; } 
 <p id="myP">Some text<span onclick="myFunc()"> to change</span></p> 

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

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