【发布时间】:2021-08-27 11:29:32
【问题描述】:
在将数组(例如“01b,02b,03c”)转换为选择器列表“#01b,#02b,#03c”时需要帮助,我可以将其用作 jQuery 中的选择器列表
HTML
<input type="radio" id="01b"/>
<input type="radio" id="02b"/>
<input type="radio" id="03c"/>
JavaScript
var arr = ['01b','02b','03c'];
// var newArr = would be a list of selectors, like ['#01b','#02b','#03c'];
// then I would use it in the JavaScript to pre-check radio buttons
$(newArr).prop('checked', true);
所以输出会是这样的
<input type="radio" id="01b" checked="checked"/>
<input type="radio" id="02b" checked="checked"/>
<input type="radio" id="03c" checked="checked"/>
我尝试过使用类似的东西
var newArr = arr.each(function() {
return '#'+ $(this);
});
但似乎远非有效;
【问题讨论】:
-
为什么不干脆做
$(arr).each(function(i) { $("input[id=" + arr[i] + "]").prop("checked", true)})? -
嗨,谢谢,应该够了,谢谢 :) 我需要先解决我这边的另一个问题。那我试试看。
标签: javascript jquery arrays css-selectors