[英]I am trying to combine a string while looping
如果嘗試選中前兩個框,我嘗試獲取的結果將是12。如果選中了3個框,則結果將是1 23。x出現為未定義。 我認為這與變量作用域有關,但是即使我在輸入函數中查看x,它一次只顯示1個選擇,也不會合並它們。
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
function MLSNumbersSelected()
{
$("input:checkbox").each(function(){
var $this = $(this);
if($this.is(":checked")){
var x = x+" "+$this.attr("id");
}
});
alert(x); //should equal what is checked for example 1 or 1 2.
}
</script>
</head>
<body>
<p id="checkBoxes">
<input type="checkbox" class="checkBoxClass" id="1" />1<br/>
<input type="checkbox" class="checkBoxClass" id="2" />2<br/>
<input type="checkbox" class="checkBoxClass" id="3" />3</p>
<p>
Check off some options then click button.
<input type="button" name="button" id="button" value="Click to Test" onClick="MLSNumbersSelected()">
</p>
</body>
您每次在循環中都定義x,而是定義一次x,並在循環中附加到該x。 例如:
<script>
function MLSNumbersSelected()
{
var x;
$("input:checkbox").each(function(){
var $this = $(this);
if($this.is(":checked")){
x += " "+$this.attr("id");
}
});
alert(x); //should equal what is checked for example 1 or 1 2.
}
</script>
您必須在.each()
循環外聲明x。 現在,它在.each()
循環內聲明,然后在調用下一個回調之前超出范圍,因此您無法從一個回調到下一個回調累積它的值:
function MLSNumbersSelected() {
var x = "";
$("input:checkbox").each(function(){
if (this.checked) {
x += " " + this.id;
}
});
console.log(x);
}
僅供參考,我還從循環內部刪除了jQuery的用法,因為當直接DOM屬性為您提供所需的一切時,就沒有必要了。
您還可以通過將:checked
添加到選擇器中,讓選擇器為您完成工作,使其僅選擇已選中的復選框。 並且,然后可以使用.map()
和.join()
來更輕松地創建列表:
function MLSNumbersSelected() {
var x = $("input:checkbox:checked").map(function(){
return this.id;
}).get().join(" ");
console.log(x);
}
您在循環中重新初始化x。 這應該可以解決您的問題:
function MLSNumbersSelected()
{
var x = '';
$("input:checkbox").each(function(){
var $this = $(this);
if($this.is(":checked")){
x = x+" "+$this.attr("id");
}
});
alert(x);
}
使用它來查看它是否滿足您的需求:
var inputs = $("input:checkbox");
inputs.each(function(i){
if(inputs.eq(i).is(":checked")){
x = x+" "+inputs.eq(i).attr("id");
}
});
$(function() { $('#button').on('click', function() { var x = $(':checkbox:checked').map(function() { return this.id; }) .get().join(' '); alert( x ); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <p id="checkBoxes"> <input type="checkbox" class="checkBoxClass" id="1" />1<br/> <input type="checkbox" class="checkBoxClass" id="2" />2<br/> <input type="checkbox" class="checkBoxClass" id="3" />3</p> <p> Check off some options then click button. <input type="button" name="button" id="button" value="Click to Test"> </p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.