我尝试复选框ID添加到使用的JavaScript语言的数组,这是我的代码:为什么不能将字符串添加到JavaScript数组中?
function checkBoxClick(e) {
alert("a");
var arr = new Array();
var rule = new Array();
var chkId = $(e).attr("id");
var tempId = "";
var tempElementId = "";
$("input[class='singlechk']").each(function() {
var elementId = $(this).attr("id");
var larr = $(this).attr("id").split('-');
tempElementId = elementId;
if (tempId == "") {
tempId = larr[0];
} else {
if (tempId != larr[0]) {
rule.push(arr);
arr = [];
arr.push(tempElementId);
} else {
arr.push(tempElementId);
}
}
});
}
我每次每复选框,其中类是“singlechk”。将id推入数组arr中,但每次都添加最后一个元素,并且第一个元素不能推入数组中。
这是我的html代码:
<div class="container">
<h3 id="question_1">饭菜质量
<span>(单选)</span>
</h3>
<br />
<input name="wjdc" class="singlechk" id="item_1-1" type="checkbox" onclick="checkBoxClick(this)" />
<span>一般</span>
<br />
<input name="wjdc" class="singlechk" id="item_1-2" type="checkbox" onclick="checkBoxClick(this)" />
<span>很好</span>
<h3 id="question_2">就餐环境
<span>(单选)</span>
</h3>
<br />
<input name="wjdc" class="singlechk" id="item_2-3" type="checkbox" onclick="checkBoxClick(this)" />
<span>很好</span>
<br />
<input name="wjdc" class="singlechk" id="item_2-4" type="checkbox" onclick="checkBoxClick(this)" />
<span>一般</span>
</div>
这是正确的结果可能是:
var rule = [["item_1-1", "item_1-2"], ["item_2-3", "item_2-4"]];
我的问题是:为什么阵列跳投输出
var rule = [["item_1-2"], ["item_2-4"]];
? – Satpal
我想清空旧数组 – Dolphin