如何在 JavaScript 中更改按钮文本或链接文本? [英] How to change button text or link text in JavaScript?

查看:29
本文介绍了如何在 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";
   }
}

据我所知,按钮文本(<button id="myButton">Lock</button>)就像任何链接文本
(<a href="#">Lock</a>).所以它是一个按钮的事实并不重要.但是,我无法访问按钮文本并对其进行更改.

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), == "Lock", == 'Lock',但没有任何效果.

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.

Or since you're dealing with a single text node, use .firstChild.data in the same manner.

另外,让我们明智地使用变量,通过缓存 getElementById 的结果来减少代码并消除冗余的 DOM 选择.

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";
   }
}

或者像这样更紧凑:

function toggleText(button_id)  {
   var text = document.getElementById(button_id).firstChild;
   text.data = text.data == "Lock" ? "Unlock" : "Lock";
}

这篇关于如何在 JavaScript 中更改按钮文本或链接文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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