使用javascript动态更改span文本并保留原始文本 [英] Using javascript to alter span text dynamically and keeping the original text

查看:106
本文介绍了使用javascript动态更改span文本并保留原始文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

现在在我的javascript代码中,我必须在span xyz >动态。如果我尝试通过id获取对 code> xyz 的引用,然后尝试更改其innerHTML,那么已经存在的跨度 xyz 会丢失。

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

如果我保留超出范围的额外代码,由于某些CSS效果,它会出现在新行中。由于某些原因,我无法改变css。

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.

推荐答案

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

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.

这篇关于使用javascript动态更改span文本并保留原始文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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