如何更改JavaScript的按钮上的文字或链接文字? [英] How to change button text or link text in JavaScript?
问题描述
我有这样的HTML按钮:
I have this HTML button:
<button id="myButton" onClick="lock(); toggleText(this.id);">Lock</button>
这是我的 toggleText
JavaScript函数:
And this is my toggleText
JavaScript function:
function toggleText(button_id)
{
if (document.getElementById('button_id').text == "Lock")
{
document.getElementById('button_id').text = "Unlock";
}
else
{
document.getElementById('button_id').text = "Lock";
}
}
据我所知,按钮上的文字(&LT;按钮的id =myButton的&GT;的Lock&LT; /按钮&GT;
),就像任何链接文本结果
(&LT; A HREF =#&GT;的Lock&LT; / A&GT;
)。因此,事实上,这是一个按钮无所谓。但是,我无法访问按钮上的文字并改变它。
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')
,(button_id)
, ==锁定
, =='锁定'
,但没有任何工程。
I tried ('button_id')
, (button_id)
, == "Lock"
, == 'Lock'
, but nothing works.
如何访问和更改按钮文本(而不是值)或链接文字?
推荐答案
修改的.text
到 .textContent
来获取/设置文本内容。
Change .text
to .textContent
to get/set the text content.
或者,因为你正在处理一个单一的文本节点,以同样的方式使用 .firstChild.data code>。
Or since you're dealing with a single text node, use .firstChild.data
in the same manner.
此外,让我们合理地使用一个变量,并享受一些code降低和通过缓存的结果,消除多余的DOM选择的getElementById
。
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
.
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";
}
这篇关于如何更改JavaScript的按钮上的文字或链接文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!