【问题标题】:Uncaught TypeError: Object has no method 'setAttribute'未捕获的类型错误:对象没有方法“setAttribute”
【发布时间】:2013-08-25 03:21:36
【问题描述】:

我的嵌套 for 循环遇到了一些问题。我正在尝试确定表单中选中复选框的值。有人告诉我,整个事情的格式应该是这样的:

for(checkboxes loop){
   for(item.appointmentType[1] loop){
      if(statement conditional){
          set checks code
      }
   }
}

但我似乎无法正确编写它,因为我收到一条错误消息, 未捕获的类型错误:对象没有方法“setAttribute”

下面是我正在使用的代码。谁能帮我纠正一下,可能知道我在说什么?

var checkboxes = document.forms[0].appointmentType;
for(var i=0; i<checkboxes.length; i++){
   for(var j=0; j<item.appointmentType[1].length; j++){
      if(checkboxes[i].value === item.appointmentType[1][j]){
        item.appointmentType[1][j].setAttribute("checked", "checked");
      }
   }
}

这是与 javascript 一起使用的 HTML 代码。所有的 javascript 都包含在它自己的 .js 文件中。

<ul><span class="lab">
<li><input type="checkbox" checked value="Get A Free Estimate" id="Get A Free Estimate"
    name="appointmentType" /><label for="getAFreeEstimate"><span class="gfe">Get A FREE
    Estimate</span></label></li>
<li><input type="checkbox" value=" Lawn Service" id="lawnService" name="appointmentType"/
    <label for="lawnService"><span class="ls">Lawn Service</span></label></li>
<li><input type="checkbox" value=" Sprinkler System Service" id="sprinklerSystemService"
    name="appointmentType" /><label for="sprinklerSystemService"><span
    class="sss">Sprinkler System Service</span></label></li>
<li><input type="checkbox" value=" Flower Bed Maintenance" id="flowerBedMaintenance"
    name="appointmentType" /><label for="flowerBedMaintenance"><span class="fbm">Flower
    Bed Maintenance</span></label></li>
<li><input type="checkbox" value=" Hedge/Tree Service" id="hedgeTreeService"
    name="appointmentType" /><labe for="hedgeTreeService"><span class="hts">Hedge / Tree
    Service</span></label></li>
<li><input type="checkbox" value=" Handyman Services" id="handymanServices"
    name="appointmentType" /><label for="handymanServices"><span class="hs">Handyman
    Services</span></label></li>
<li><input type="checkbox" value=" Other" id="other" name="appointmentType" /><label
    for="other"><span class="otr">Other</span></label></li></span></ul><br/>

【问题讨论】:

  • “item”应该如何获得价值?
  • 你能展示一下这段代码的 HTML 吗?

标签: javascript for-loop nested-loops


【解决方案1】:

这一行:

item.appointmentType[1][j].setAttribute("checked", "checked");

应该是:

checkboxes[i].checked = true;

【讨论】:

  • 嘿,这似乎没有任何错误。谢谢。现在我只是提交它以供批准,看看它是否正确。谢谢。
  • 感谢给我这个答案的人。它是正确的,并且工作正常,没有任何错误。
【解决方案2】:

如果您在项目中渲染了 Jquery,认为您可以将您的行替换为:

复选框 = $('input[type="checkbox"]');

$(checkboxes[i]).prop('checked',true);

也许会有帮助

【讨论】:

  • for 循环需要按照上述格式进行格式化。如果您愿意,请将其完整地写下来,以便我可以准确地看到您所描述的内容。谢谢。
猜你喜欢
  • 2013-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-05
相关资源
最近更新 更多