Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

html - How to change button text or link text in JavaScript?

I have this HTML button:

<button id="myButton" onClick="lock(); toggleText(this.id);">Lock</button>

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

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.

I tried ('button_id'), (button_id), == "Lock", == 'Lock', but nothing works.

How can I access and change a button text (not value) or a link text?

question from:https://stackoverflow.com/questions/12679813/how-to-change-button-text-or-link-text-in-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change .text to .textContent to get/set the text content.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...