简体   繁体   English

使用Javascript更新单选按钮标签innerHTML后,如何防止单选按钮消失?

[英]How can I prevent a radio button from disappearing after updating the radio button label innerHTML with Javascript?

The radio button I'm using disappears when I try to update the radio button label's innerHTML using Javascript. 当我尝试使用Javascript更新单选按钮标签的innerHTML时,我使用的单选按钮会消失。

Here is the HTML, as you can see I have the radio button inside the label, so it can be on the same line. 这是HTML,您可以看到我在标签内有单选按钮,因此它可以在同一行上。

<label for="radio" name="firstElement" id="firstElement">
   <input type="radio" name="radio" id="radio" /> Loading number
</label>

Below is the Javascript that updates the label's innerHTML when the page loads, and it also removes the radio button. 以下是在页面加载时更新标签的innerHTML的Javascript,并且它还删除了单选按钮。 I'm guessing that is because the radio button is considered part of the innerHTML since it's inside of the label. 我猜这是因为单选按钮位于标签内部,因此被视为innerHTML的一部分。

firstElement.innerHTML = "It works!";

My questions is, how do I prevent the radio button from disappearing? 我的问题是,如何防止单选按钮消失?

I have tried using the method that includes the nextSibling.nodeValue, but whenever I do, the nodeValue always comes back as undefined. 我尝试使用包含nextSibling.nodeValue的方法,但是无论何时,nodeValue总是以未定义的形式返回。

Add a span to the element, and set the text on it. 将跨度添加到元素,然后在其上设置文本。

 document.querySelector('#firstElementText').innerText = 'It works!'; 
 <label for="radio" name="firstElement" id="firstElement"> <input type="radio" name="radio" id="radio" /> <span id="firstElementText">Loading number</span> </label> 

Add a span around the text you want to change and select that span and change only that text: 在要更改的文本周围添加跨度,然后选择该跨度并仅更改该文本:

 var firstElement = document.getElementById('firstElement').getElementsByTagName('span')[0]; firstElement.innerHTML = "It works!"; 
 <label for="radio" name="firstElement" id="firstElement"> <input type="radio" name="radio" id="radio" /> <span>Loading number</span> </label> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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