动态添加单选按钮标签 - JavaScript

Dynamically add Radio Button Labels - JavaScript

无法将标签动态分配给单选按钮。除 innerHTML 之外,所有代码均正常工作。无法找出原因。在此先感谢您的帮助。

<!DOCTYPE html>
<html>

    <body>
        <form id="myForm">
        </form>
        <br>
        <button onclick="addRadio()">Add radio buttons!</button>

        <script>

            // This function will add a new Radio buttons to the above
            count = 0;
            function addRadio()
            {
                count++;
                //Create input type
                var myRadio = document.createElement("input");
                var myName = document.createElement("testRadio");
                var myBreak = document.createElement("br");
                var myLabel = document.createElement("label");
                var labelMessage = "Radio Button: " + count;
                var labelId = "l" + count;
                myRadio.setAttribute("type", "radio");
                myRadio.setAttribute("name", "testRadio");
                myRadio.setAttribute("value", "Radio Button: " + count);
                myLabel.setAttribute("for", labelId);               
                myRadio.setAttribute("id", labelId);
                document.getElementById('myForm').appendChild(myRadio);
                document.getElementById('myForm').appendChild(myLabel);
                document.getElementById('myForm').appendChild(myBreak);
                document.getElementById('labelId').innerHTML = 'labelMessage';  
            }
            
        </script>
        
    </body>
</html>

下一行本身可能不会插入标签元素。最好做

myLabel.innerHTML = 'labelMessage';

因为您已经在变量中拥有该元素。

代码中有一个小错误。

在 .innerHTML 之前,您通过 id 'labelId' 获取元素作为字符串。

您需要 select 将 labelID 作为变量,因此:

document.querySelector(`label[for="${labelId}"]`).innerHTML = labelMessage;