请看一下这段代码,让我知道为什么我无法加载阵列?
$(':checkbox[name=items]').on('change', function() {
var arr = $(':checkbox[name=items]:checked').map(function() {
return this.id;
})
.get();
$("#p-tap").on("click", function(){
console.log(arr);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input type="checkbox" name="items" value="Item_1" /> Lower Development Cost <br />
<input type="checkbox" name="items" value="Item_2" /> Higher Energy Production<br />
<input type="checkbox" name="items" value="Item_3" /> Further From Human Populations<br />
<input type="checkbox" name="items" value="Item_3" /> Smaller Construction Footprint<br />
</div>
<button id="p-tap"> Print</button>
&#13;
答案 0 :(得分:1)
Transaction
已定义为var arr
,这使其成为局部变量而非全局范围
将您的代码更改为
inside checkbox change closure
var arr;
$(':checkbox[name=items]').on('change', function() {
arr = $(':checkbox[name=items]:checked').map(function() {
return this.id;
})
.get()});
&#13;
var arr;
$(':checkbox[name=items]').on('change', function() {
arr = $(':checkbox[name=items]:checked').map(function() {
return this.value;
})
.get();
});
$("#p-tap").on("click", function() {
console.log(arr);
$('#result').text(arr);
});
&#13;