javascript 错误:无法读取未定义的属性“已检查”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17706058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:16:39  来源:igfitidea点击:

Error: Cannot read property 'checked' of undefined

javascripthtml

提问by Steven07

I'm trying to store the result of checked checkboxes in local storage but when I try to save I get the error mentioned above.

我正在尝试将选中的复选框的结果存储在本地存储中,但是当我尝试保存时出现上述错误。

Not quite sure what is undefined since I see the property in my code. Here's the code:

不太确定什么是未定义的,因为我在代码中看到了该属性。这是代码:

var getCheckboxValue = function (){
    var checkboxes = document.forms[0].features;
    for(var i=0, j=checkboxes.length; i<j; i++){
        if(checkboxes[i].checked){
        console.log(checkboxes[i].value);
            //featuresValue = $("features").value();
        }else{
            checkboxes = "No"
        }
        }
    }

var storeData = function (){
    var id = Math.floor(Math.random()*10000001);
    //getSelectedRadio();
    getCheckboxValue();
    var item = {};
        item.brand = ["Brand",$("brand").value];
        item.model = ["Model",$("model").value];
        item.comments = ["comments",$("comments").value];
        //item.acoustic = ["acoustic", acousticValue]; 
        item.features = ["features",checkboxes];

    //Save data into local storage: Use Stringify to convert our object to a string
    localStorage.setItem(id,JSON.stringify(item));
    alert("Contact Saved!");
}


//set link & submit click events
var save = $("button");
save.addEventListener("click", storeData);

and here's the relevant html:

这是相关的html:

<li>Features:
                    <ul>
                        <li><input type="checkbox"  name="features" value = "Cutaway" id="cutaway" /><label for="cutaway">Cutaway</label></li>
                        <li><input type="checkbox"  name="features" value = "Finished" id="finished" /><label for="finished">Finished</label></li>
                        <li><input type="checkbox"  name="features" value = "Inlay" id="inlay" /><label for="inlay">Inlay</label></li>
                        <li><input type="checkbox"  name="features" value = "Wide Neck" id="wneck" /><label for="wneck">Wide Neck</label></li>
                        <li><input type="checkbox"  name="features" value = "Left-handed" id="lhanded" /><label for="lhanded">Left-handed</label></li>
                    </ul>
                </li>

Alternatively, here's a link to the full code on github:

或者,这里是 github 上完整代码的链接:

https://github.com/b80266/VFW-Project-2/blob/master/additem.html

https://github.com/b80266/VFW-Project-2/blob/master/additem.html

https://github.com/b80266/VFW-Project-2/blob/master/main.js

https://github.com/b80266/VFW-Project-2/blob/master/main.js

回答by Ian

The problem is that you're overwriting the value of checkboxes(the original collection of checkboxes in the form) here:

问题是您在checkboxes此处覆盖了(表单中的原始复选框集合)的值:

}else{
    checkboxes = "No"
}

This is insideof the loop...the loop that is iterating through checkboxes. It is now iterating over the characters in the string "No", not the collection of elements you originally retrieved. This string is only 2 characters long, while your original loop has a cached value of checkboxes.length(5 elements) stored in jwhich is not updated each iteration, meaning it will loop past i = 1, accessing the third, fourth and fifth indexes, which are now undefined.

这是循环内部...循环遍历checkboxes。它现在迭代字符串“No”中的字符,而不是您最初检索的元素集合。这个字符串只有 2 个字符长,而您的原始循环有一个缓存值checkboxes.length(5 个元素)存储在j其中,每次迭代都不会更新,这意味着它将循环过去i = 1,访问现在未定义的第三、第四和第五个索引。

Another "problem", is that in your storeDatafunction, you're calling getCheckboxValuebut not storing it anywhere...then later you're referencing some checkboxesvariable later - item.features = ["features",checkboxes];. You need to store the result, then use that variable. Here's a demo that seems to work with some assuming HTML:

另一个“问题”是,在您的storeData函数中,您正在调用getCheckboxValue但未将其存储在任何地方……然后稍后您将引用某个checkboxes变量 - item.features = ["features",checkboxes];。您需要存储结果,然后使用该变量。这是一个演示,它似乎适用于一些假设的 HTML:

var $ = function (id) {
    return document.getElementById(id);
};

var getCheckboxValue = function () {
    var checkboxes = document.forms[0].features;
    for (var i = 0, j = checkboxes.length; i < j; i++) {
        if (checkboxes[i].checked) {
            console.log(checkboxes[i].value + " is checked");
        } else {
            //checkboxes = "No";
            console.log(checkboxes[i].value + " is not checked");
        }
    }
};

var storeData = function () {
    var id = Math.floor(Math.random()*10000001);
    var checkedBoxes = getCheckboxValue();
    var item = {};
    item.brand = ["Brand",$("brand").value];
    item.model = ["Model",$("model").value];
    item.comments = ["comments",$("comments").value];
    item.features = ["features",checkedBoxes];

    //Save data into local storage: Use Stringify to convert our object to a string
    localStorage.setItem(id,JSON.stringify(item));
    alert("Contact Saved!");
};


//set link & submit click events
var save = $("button");
save.addEventListener("click", storeData, false);

DEMO:http://jsfiddle.net/jmUXY/1/

演示:http : //jsfiddle.net/jmUXY/1/

回答by Alcides Soares FIlho

Based on Ian's suggestions, you can check all radios in any number of forms. See exemple:

根据 Ian 的建议,您可以以任意数量的形式检查所有收音机。参见示例:

jQuery(document).ready(function() {

 $("input[type='radio']").change(function() {
  if (this.checked) {
   //Do stuff
   //console.log("foi clicado");
   var marcados = 0;
   var naoMarcados = 0;
   //conta numero de checados
   var inputElems = document.getElementsByTagName("input"),
    count = 0;
   for (var i = 0; i < inputElems.length; i++) {
    if (inputElems[i].type == "radio" && inputElems[i].checked === true) {
     count++;
     marcados = count;
    } else {
     naoMarcados = naoMarcados + 1;
    }
   }
   $("#marcados").html("Total de Marcados: " + marcados);
   $("#naomarcados").html("Total de N?o Marcados: " + naoMarcados);

  }
 });
});
 <script
  src="https://code.jquery.com/jquery-3.2.1.js"
  integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE="
  crossorigin="anonymous"></script>
  <p>
  FORM 1
  </p>
 <form id="1">
 <input type="radio">Em grau muito alto
  <input type="radio">Em grau alto
   <input type="radio">Em grau médio 
  <input type="radio" CHECKED>Em grau baixo
  <input type="radio">Em grau muito baixo
  <input type="radio">N?o observo
  </form>
  <hr>

  <p>
  FORM 2
  </p>
  <form id="2">
 <input type="radio">Em grau muito alto
  <input type="radio">Em grau alto
   <input type="radio">Em grau médio 
  <input type="radio">Em grau baixo
  <input type="radio">Em grau muito baixo
  <input type="radio">N?o observo
  </form>
  <hr>
  <div id="marcados"></div>
  <div id="naomarcados"></div>