简体   繁体   中英

Changing contents of button when clicked

For some reason I'm stumped trying to change the contents of a button when clicked. Here is my code:

<!DOCTYPE html>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Exam 2</title>
</head>
<body>
    <div>
<p>
    <button id="button">Start</button>
    </p></div>
    <p id="result"></p>
    <div><p>
        <img src="turret-portal.jpg" height="150" width="100"/>
        </p></div>

    <script>
var button=document.getElementById("button");
button.onclick = function() {
     button.value = "test";
};    
    </script>
    </body>
</html>

I feel like I am fundamentally misunderstanding something.

Thanks for your help

edit:

This also doesn't work:

<!DOCTYPE html>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Exam 2</title>
</head>
<body>
    <div>
<p>
    <button id="button">Start</button>
    </p></div>
    <p id="result"></p>
    <div><p>
        <img src="turret-portal.jpg" id="pic" height="150" width="100"/>
        </p></div>

    <script>
document.getElementById("button").onclick = function() {
     document.getElementById("button").innerText = "test";
};    
    </script>
    </body>
</html>

You don't want to change the value attribute. You want to modify the text content.

So you can replace button.value = "test"; with button.innerText = "test"; .

Also, you can change the data for the text node that's inside your button element, as stated in this other answer .

Change your javascript to this:

var button=document.getElementById("button");
button.onclick = function() {
    button.innerHTML = "test";
};

You would use .value if it was <input type=button/>

Here is working fiddle: https://jsfiddle.net/q0g8c78q/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM