Javascript 使用javascript动态更改跨度文本并保留原始文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4491050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:37:36  来源:igfitidea点击:

Using javascript to alter span text dynamically and keeping the original text

javascripthtml

提问by akshay

I have a html page, inside which i have following code snippet, depending on which case we're following:

我有一个 html 页面,其中有以下代码片段,具体取决于我们遵循的情况:

CASE 1)    <p> <span id ="xyz">  some code here  </span> </p>
CASE 2)    <p> <span id ="xyz">   </span> some code here </p>

Now in my javascript code I have to write values in span xyzdynamically. If I try to do get reference to span xyzby id and then try to alter its innerHTML, then the html already present in span xyzis lost.

现在在我的 javascript 代码中,我必须xyz动态地在 span 中写入值。如果我尝试xyz通过 id获取对 span的引用,然后尝试更改其 innerHTML,则 span 中已经存在的 htmlxyz将丢失。

If I keep extra code outside the span, it appears on new line due to some css effects. I cannot alter css due to some reasons.

如果我在跨度之外保留额外的代码,由于某些 css 效果,它会出现在新行上。由于某些原因,我无法更改 css。

回答by Konerak

You can just store the current value in a String, and then modify this string:

您可以将当前值存储在一个字符串中,然后修改此字符串:

var mySpan = document.getElementById('xyz').innerHTML;
mySpan += ' and this gets added after the some code here';
document.getElementById('xyz').innerHTML = mySpan;

or faster and more shorthand,

或者更快更速记,

document.getElementById('xyz').innerHTML = document.getElementById('xyz').innerHTML + ' new text after'; //to add text after the existing text
document.getElementById('xyz').innerHTML = 'your new text before ' + document.getElementById('xyz').innerHTML; //to add text before.

回答by dheerosaur

You can append a new text node to span, if you want to keep the old text.

如果要保留旧文本,可以将新文本节点附加到 span。

var newtext = document.createTextNode(" new text ");
var spanXyz = document.getElementById("xyz");
spanXyz.appendChild(newtext);

Refer these: createTextNode, appendChild

参考这些:createTextNodeappendChild

Edit: To add new text at the beginning, you can use something like

编辑:要在开头添加新文本,您可以使用类似

spanXyz.textContent = "new text " + spanXyz.textContent;

回答by Sundar Singh

If you are not using jquery :

如果您不使用 jquery :

document.getElementById('xyz').innerHTML=   document.getElementById('xyz').innerHTML + "XYZ";

If you are using jquery:

如果您使用的是 jquery:

 $("#xyz").append("xyz");

回答by Pradeep Singh

document.getElementById('xyz').innerHTML = 'some code here' + 'dynamically code';

or

或者

document.getElementById('xyz').innerHTML = 'dynamically code' + 'some code here' ;