JQuery.each失败了SOMETIMES

时间:2011-06-23 18:17:15

标签: jquery

循环使用一堆复选框,SOMETIMES失败。 检查部分或全部框时,不会输入.each函数,因此即使存在“已选中”框,也会显示“未选中复选框”警告。

$(document).ready(function() {
  $("#submitme").click(function() {
    var urls = [];
    $("#edit :checked").each(function() {
      var obj = {};
      obj.url = $(this).val();
      urls.push(obj);
    });
    if (0 < urls.length) {
      $.post('/myurl', {urls: JSON.stringify(urls)});
    }
    else {
      alert("no checkboxes were checked!");
    }
   });
});

<div id="edit">
  <input type="checkbox" name="first"  value="first_url"/>
  <input type="checkbox" name="second" value="second_url"/>
  <button id="submitme">submit</button>
</div>

jsFiddle Example

4 个答案:

答案 0 :(得分:1)

没有问题的答案。这个问题只存在于Opera中,因此它与浏览器有关。

答案 1 :(得分:0)

似乎对我工作正常:http://jsfiddle.net/maniator/BFuaZ/

确保代码中的其他任何地方都没有javascript错误。

答案 2 :(得分:0)

你的选择器应该是     $(“#edit input:checked”)

答案 3 :(得分:0)

我认为你有一些语法问题。尝试:

$(document).ready(function() {
  $("#submitme").click(function() {
    var urls = new Array();
    $("#edit :checked").each(function() {
      var obj = new Object();
      obj.url = $(this).val();
      urls.push(obj);
    });

    if (0 < urls.length){
      $.post('/myurl', {urls: JSON.stringify(urls)});
    }else {
      alert("no checkboxes were checked!");
   }
   });
   });

如果你在JSLint输出中查看jsfiddle,你会得到这个

Error:

Problem at line 2 character 25: Use the array literal notation [].

var urls = new Array();

Problem at line 4 character 21: Use the object literal notation {}.

var obj = new Object();

Problem at line 9 character 7: Expected '{' and instead saw 'console'.

console.log(urls)

Problem at line 9 character 24: Missing semicolon.

console.log(urls)

Problem at line 11 character 7: Expected '{' and instead saw 'alert'.

alert("no checkboxes were checked!");

Implied global: $ 1,3,5, console 9, alert 11