我需要你的帮助。
如何从数组中获取值并使用HTML 5的数据属性检查(勾选)相关的复选框?
即
var x = "[monday,thursday]"
<input name="recurr_weekday" type="checkbox" data-weekday="sunday">
<input name="recurr_weekday" type="checkbox" data-weekday="monday">
<input name="recurr_weekday" type="checkbox" data-weekday="tuesday">
<input name="recurr_weekday" type="checkbox" data-weekday="wednesday">
<input name="recurr_weekday" type="checkbox" data-weekday="thursday">
<input name="recurr_weekday" type="checkbox" data-weekday="friday">
<input name="recurr_weekday" type="checkbox" data-weekday="saturday">
...经过一些处理后,下面的复选框会勾选:
<input name="recurr_weekday" type="checkbox" data-weekday="monday">
<input name="recurr_weekday" type="checkbox" data-weekday="thursday">
答案 0 :(得分:0)
您可以使用属性选择器
var x = ["monday", "thursday"];
for (let prop of x) {
document.querySelector("input[type=checkbox][data-weekday=" + prop + "]")
.checked = true;
}
答案 1 :(得分:0)
您可以使用以下代码:
x.forEach(function (weekDay){
var htmlElement = document.querySelectorAll('[data-weekday="'+weekDay+'"]').checked = true;
});
它将迭代数组x,每个值我们将找到具有data-weekday value属性的相应元素。
答案 2 :(得分:0)
这是另一个有一些优点的解决方案:
data-weekday="monday"
。recurr_weekday
个复选框。
document.querySelector('button').onclick = checkTheDays;
var myDays = ["monday", "thursday"];
function checkTheDays() {
var checkboxes = document.querySelectorAll('[name="recurr_weekday"]');
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = myDays.indexOf(checkboxes[i].getAttribute('data-weekday')) > -1;
}
}
&#13;
Week 1:
<input name="recurr_weekday" type="checkbox" data-weekday="sunday">
<input name="recurr_weekday" type="checkbox" data-weekday="monday">
<input name="recurr_weekday" type="checkbox" data-weekday="tuesday">
<input name="recurr_weekday" type="checkbox" data-weekday="wednesday">
<input name="recurr_weekday" type="checkbox" data-weekday="thursday">
<input name="recurr_weekday" type="checkbox" data-weekday="friday">
<input name="recurr_weekday" type="checkbox" data-weekday="saturday">(Initially all unchecked)
<br />Week 2:
<input name="recurr_weekday" type="checkbox" data-weekday="sunday" checked>
<input name="recurr_weekday" type="checkbox" data-weekday="monday" checked>
<input name="recurr_weekday" type="checkbox" data-weekday="tuesday" checked>
<input name="recurr_weekday" type="checkbox" data-weekday="wednesday" checked>
<input name="recurr_weekday" type="checkbox" data-weekday="thursday" checked>
<input name="recurr_weekday" type="checkbox" data-weekday="friday" checked>
<input name="recurr_weekday" type="checkbox" data-weekday="saturday" checked>(Initially all checked)
<br />
<button>
Check Mondays and Thursdays
</button>
&#13;