简体   繁体   中英

Why is my function from onlick not changing the innerHTML?

I am a beginner in Javascript, and I am trying to create a website that has some questions for people to fill out.

So right now, I have something like:

<head>
    <script>
        function wrong(self) {
            self.innerHTML = "Wrong :(";
        }
        function right(self) {
            self.innerHTML = "Right!";
        }
    </script>
</head>
<body>
    Who is the better team?: <br>
    <input type="checkbox" name = "q1" value="Celtics" onclick="wrong(this)">Celtics<br><br>
    <input type="checkbox" name = "q1" value="Lakers" onclick="right(this)">Lakers<br><br>
</body>

But when I actually create my page with the checkboxes, the text on the right doesn't get changed when I click either of the checkboxes. I have also tried changing the type to "button" but that doesn't have its innerHTML changed either.

I have seen some previous answers saying that I might be trying to change something before an element is loaded. However, if I am calling the function using the "onclick" attribute inside the said element, then I believe it must be loaded at the time of calling.

Your help is appreciated!

Inputs cannot have children. They're like <img> s. The Celtics and Lakers exist in separate text nodes (that are not children). Assigning to the innerHTML of the input does nothing.

Put the texts into standalone elements of their own, and then you'll be able to change their text.

 function wrong(self) { self.nextElementSibling.textContent = "Wrong:("; } function right(self) { self.nextElementSibling.textContent = "Right;"; }
 Who is the better team?: <br> <input type="checkbox" name="q1" value="Celtics" onclick="wrong(this)"> <div>Celtics</div> <input type="checkbox" name="q1" value="Lakers" onclick="right(this)"> <div>Lakers</div>

(while it would be technically possible to select and change the text nodes in your original HTML, having elements to change instead of text nodes usually makes more sense)

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