gpt4 book ai didi

javascript - 从数组中获取值并检查(勾选)相关复选框

转载 作者:行者123 更新时间:2023-11-28 05:07:26 26 4
gpt4 key购买 nike

我需要你的帮助。

如何从数组中获取值并使用 HTML 5 的 data 属性选中(勾选)其相关复选框?

即。

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">

最佳答案

这是另一个具有一些优点的解决方案:

  • 即使同一天有多个复选框,例如两个带有 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;
}
}
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>

关于javascript - 从数组中获取值并检查(勾选)相关复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41622558/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com