代码之家  ›  专栏  ›  技术社区  ›  paul

JavaScript:setAttribute函数失败

  •  1
  • paul  · 技术社区  · 6 年前

    https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_getelementsbyname_loop

    发件人:

    <!DOCTYPE html>
    <html>
    <body>
    
    Cats:  <input name="animal" type="checkbox" value="Cats">
    Dogs:  <input name="animal" type="checkbox" value="Dogs">
    
    <p>Click the button to check all checkboxes that have a name attribute with the value "animal".</p>
    
    <button onclick="myFunction()">Try it</button>
    
    <script>
    function myFunction() {
        var x = document.getElementsByName("animal");
        var i;
        for (i = 0; i < x.length; i++) {
            if (x[i].type == "checkbox") {
                x[i].checked = true;
            }
        }
    }
    </script>
    
    </body>
    </html>
    

    致: i、 我想更改value属性的值。

      for (i = 0; i < x.length; i++) {
        if (x[i].type == "checkbox") {
            x[i].setAttribute("value", "camels");
        }
    }
    

    这并没有改变什么,但我做错了什么?

    编辑:要求更改DOM而不是HTML中的属性。

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  4
  •   Pabs123    6 年前

    Looks to be doing what is expected . 这个 value 每个复选框的属性更改为camels。

    如果您试图更改复选框旁边的文本,则需要将其包装在其自己的元素中(可能是 p )并更改 text 价值 将仅更改该复选框对应的实际数据值。

        2
  •  2
  •   Blazes    6 年前

    Cats:  <input name="animal" type="checkbox" value="camels">
    Dogs:  <input name="animal" type="checkbox" value="camels">