如何在 JavaScript 中更改按钮文本或链接文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12679813/
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
How to change button text or link text in JavaScript?
提问by tempy
I have this HTML button:
我有这个 HTML 按钮:
<button id="myButton" onClick="lock(); toggleText(this.id);">Lock</button>
And this is my toggleText
JavaScript function:
这是我的toggleText
JavaScript 函数:
function toggleText(button_id)
{
if (document.getElementById('button_id').text == "Lock")
{
document.getElementById('button_id').text = "Unlock";
}
else
{
document.getElementById('button_id').text = "Lock";
}
}
As far as I know, button text (<button id="myButton">Lock</button>
) is just like any link text
(<a href="#">Lock</a>
). So the fact that it's a button doesn't matter. However, I can't access the button text and change it.
据我所知,按钮文本 ( <button id="myButton">Lock</button>
) 就像任何链接文本
( <a href="#">Lock</a>
)。所以它是一个按钮的事实并不重要。但是,我无法访问按钮文本并对其进行更改。
I tried ('button_id')
, (button_id)
, == "Lock"
, == 'Lock'
, but nothing works.
我试过('button_id')
, (button_id)
, == "Lock"
, == 'Lock'
,但没有任何效果。
How can I access and change a button text (not value) or a link text?
如何访问和更改按钮文本(不是值)或链接文本?
回答by I Hate Lazy
Change .text
to .textContent
to get/set the text content.
更改.text
为.textContent
获取/设置文本内容。
Or since you're dealing with a single text node, use .firstChild.data
in the same manner.
或者因为您正在处理单个文本节点,请.firstChild.data
以相同的方式使用。
Also, let's make sensible use of a variable, and enjoy some code reduction and eliminate redundant DOM selection by caching the result of getElementById
.
此外,让我们明智地使用变量,通过缓存getElementById
.
function toggleText(button_id)
{
var el = document.getElementById(button_id);
if (el.firstChild.data == "Lock")
{
el.firstChild.data = "Unlock";
}
else
{
el.firstChild.data = "Lock";
}
}
Or even more compact like this:
或者像这样更紧凑:
function toggleText(button_id) {
var text = document.getElementById(button_id).firstChild;
text.data = text.data == "Lock" ? "Unlock" : "Lock";
}
回答by elclanrs
document.getElementById(button_id).innerHTML = 'Lock';
回答by Callum McLean
You can simply use:
您可以简单地使用:
document.getElementById(button_id).innerText = 'Your text here';
document.getElementById(button_id).innerText = 'Your text here';
If you want to use HTML formatting, use the innerHTML
property instead.
如果要使用 HTML 格式,请改用该innerHTML
属性。
回答by Anoop
Remove Quote. and use innerText instead of text
删除报价。并使用innerText而不是文本
function toggleText(button_id)
{ //-----\/ 'button_id' - > button_id
if (document.getElementById(button_id).innerText == "Lock")
{
document.getElementById(button_id).innerText = "Unlock";
}
else
{
document.getElementById(button_id).innerText = "Lock";
}
}