如果innerHTML是邪恶的,那么更好的方法是改变链接的文本? [英] If innerHTML is evil, then what's a better way change the text of a link?
本文介绍了如果innerHTML是邪恶的,那么更好的方法是改变链接的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
< a id =mylinkhref =>点击我< / a>
在JS中,您可以更改文本:
document.getElementById(mylink)。innerHTML = new_text;
在Prototype / jQuery中:
$(mylink)。innerHTML = new_text;
工作正常。否则,您必须首先替换所有的子节点,然后添加一个文本节点。为什么麻烦?
解决方案
如何
document.getElementById('mylink')。firstChild.nodeValue = new_text;
这不会受到PEZ描述的问题的困扰。
关于Triptych的评论和bobince的回复,这里是另一个解决方案:
var oldLink = document.getElementById('mylink '),
newLink = oldLink.cloneNode(false);
newLink.appendChild(document.createTextNode(new_text));
oldLink.parentNode.replaceChild(newLink,oldLink);
I know innerHTML is supposedly evil, but I think it's the simplest way to change link text. For example:
<a id="mylink" href="">click me</a>
In JS you can change the text with:
document.getElementById("mylink").innerHTML = new_text;
And in Prototype/jQuery:
$("mylink").innerHTML = new_text;
works fine. Otherwise you have to replace all of the child nodes first and then add a text node. Why bother?
解决方案
How about
document.getElementById('mylink').firstChild.nodeValue = new_text;
This won't suffer from the problems described by PEZ.
Regarding Triptych's comment and bobince's reply, here's another solution:
var oldLink = document.getElementById('mylink'),
newLink = oldLink.cloneNode(false);
newLink.appendChild(document.createTextNode(new_text));
oldLink.parentNode.replaceChild(newLink, oldLink);
这篇关于如果innerHTML是邪恶的,那么更好的方法是改变链接的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文