我有一个函数,需要循环遍历所有选择标记和复选框,获取它们的名称和值,然后将其分配给"data“对象。这是密码
data_query:->
data = {}
$('input[type="checkbox"]').each ->
data[$(this).attr('name')] = $(this).is(":checked")
$('select').each ->
data[$(this).attr('name')] = $(this).val()
# console.log data
return data结果应该是:
Object {select_one: "value", select_two: "value", ag_1: false, ag_2: true, ft_1: false, ft_2: false, bg_1: false}但我最后得到的是:
Object {select_one: "value", select_two: "value", ag_1: false} #it gets only one checkbox我理解回调的本质,我知道为什么会发生--外部功能在内部循环结束之前结束,但是我不知道如何解决这个问题。
谢谢!
编辑:这里是。它只是简单的选择标签和复选框。
<li><label for="ag_1"><input name="ag_1" type="checkbox" id="ag_1"> AG-1</label></li>
<li><label for="ag_2"><input name="ag_2" type="checkbox" id="ag_2"> AG-2</label></li>
<li><label for="ft_1"><input name="ft_1" type="checkbox" id="ft_1"> FT-1</label></li>
<li><label for="ft_2"><input name="ft_2" type="checkbox" id="ft_2"> FT-2</label></li>
<li><label for="bg_2"><input name="bg_1" type="checkbox" id="bg_2"> BG-1</label> </li>
<!-- there's a bunch of these -->
<select name="select_one" id="select_one">
<option value="">-- Select One --</option>
<option value="ac_1">AC-1</option>
<option value="ac_2">AC-2</option>
<option value="ac_3">AC-3</option>
<option value="ac_4">AC-4</option>
<option value="ac_5">AC-5</option>
<option value="ac_6">AC-6</option>
<option value="ac_7">AC-7</option>
</select> 发布于 2013-07-09 19:00:41
问题是,CoffeeScript隐式地返回要分配给data属性的值。然而,each确实将false的返回值考虑为break,并结束循环。您必须“显式地”返回undefined:
data = {}
console.log $('input[type="checkbox"]').each ->
data[$(this).attr('name')] = $(this).is(":checked")
return
$('select').each ->
data[$(this).attr('name')] = $(this).val()
return
return data(jsfiddle.org演示,产生代码)
https://stackoverflow.com/questions/17555772
复制相似问题