在我正在處理的Web應用程序中,有很多地方我有很多HTML複選框,我需要將其轉換爲選定項目的JS數組。例如:獲取所選複選框屬性的數組
<input type="checkbox" class="example" data-item="3">
<input type="checkbox" class="example" data-item="5">
<input type="checkbox" class="example" data-item="7">
<input type="checkbox" class="example" data-item="11">
然後,我有很多的邏輯是這樣的選擇的值打包成一個數組:
var items = [];
$('.example[data-item]:checked').each(function (_, e) {
items.push(Number($(e).data('item')));
});
我的問題就是這樣的:有一些不錯的方式來做到這一點一個班輪(如果需要jQuery是允許的),例如:
var items = /* magic */;
我知道我可以寫這樣的功能,我會如果沒有辦法做到這一點清楚地說明,但我正在尋找對於一些內置的JS魔術來說t可以一次完成。
爲了完整這裏有一個片段:
$('#button').click(function() {
var items = [];
$('.example[data-item]:checked').each(function (_, e) {
items.push(Number($(e).data('item')));
});
alert(JSON.stringify(items));
});
label { display: flex; align-items: center; }
div { display: inline-flex; flex-direction: column; }
button { margin: 1ex; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label><input type="checkbox" class="example" data-item="3"> Item 3</label>
<label><input type="checkbox" class="example" data-item="5"> Item 5</label>
<label><input type="checkbox" class="example" data-item="7"> Item 7</label>
<label><input type="checkbox" class="example" data-item="11"> Item 11</label>
<label><input type="checkbox" class="example" data-item="13"> Item 13</label>
<label><input type="checkbox" class="example" data-item="17"> Item 17</label>
<label><input type="checkbox" class="example" data-item="19"> Item 19</label>
<button id="button">Click Me</button>
</div>
http://api.jquery.com/jquery.map/'VAR項目= $(」例如[數據項]:檢查').map(function(){ return Number($(this).data('item')); })。get();' – Satpal
@Jason ...檢查這個小提琴http://jsfiddle.net/russcam/NxATD/ ..來源是https://stackoverflow.com/questions/6166763/jquery-multiple- checkboxes-array – Shiladitya
@Shiladitya哦真棒,那麼容易。謝謝! –