如何在Vanilla JS中做一个函数,把选中的属性放在单选输入之前?

问题描述 投票:0回答:1

我找不到解决这个问题的方法。

需要把属性检查放在选定输入前的输入上,用JavaScript把选定输入后的输入取消检查。

UPD:把输入类型改成了 "复选框",现在我需要一个函数,在最后一个复选框之前标记 "选中 "复选框,同时在复选框之前取消对后续复选框的选中。

请注意。 这个解决方案必须使用ES5兼容的语法。

请提供代码示例

<input type="checkbox" id="product-1" name="toggle">
<input type="checkbox" id="product-2" name="toggle">
<input type="checkbox" id="product-3" name="toggle">
<input type="checkbox" id="product-4" name="toggle">
<input type="checkbox" id="product-5" name="toggle">
javascript arrays radio-button preventdefault checked
1个回答
0
投票

那么,我的朋友,它可以像这样简单。

// checkbox elements
var boxes = document.getElementsByName('toggle');

// function to bind to each of the input tags' change event
function markPreceding() {

  // retrieve the value from the clicked input
  var curIndex = this.value;

  // iterate through every single checkbox named toggle
  for (var i = 0, box = boxes[i]; i < boxes.length; box = boxes[++i]) {
    // if data-index is lower or equal to curIndex, then true; else, false
    box.checked = box.value <= curIndex;
  }

}

// add function to the onchange handler of each input
for (var i = 0, box = boxes[i]; i < boxes.length; box = boxes[++i]) {
  box.onchange = markPreceding;
}
<input type="checkbox" id="product-1" name="toggle" value="1">
<input type="checkbox" id="product-2" name="toggle" value="2">
<input type="checkbox" id="product-3" name="toggle" value="3">
<input type="checkbox" id="product-4" name="toggle" value="4">
<input type="checkbox" id="product-5" name="toggle" value="5">

笔记

我将每个复选框的索引用 数据属性.

I 可以 曾用 value 属性,例如。我更喜欢使用数据属性,因为你 可能 想用 value 为别的东西。这是你的决定。 (见帖底)

我们可以检索每个属性 data-index 的HTML视图,并在JavaScript中使用 .dataset.index. 它可以是任何其他的名字,而不是 "索引"。只需记住,如果你使用多个词,如 data-my-custom-prop 在HTML中,你必须在JS中调用它为 .dataset.myCustomProp (他们得到camelCased)。

.checked 属性存储一个布尔值,所以你可以通过比较 box.dataset.index <= curIndex 将评价为 truefalse,尊重地勾选或取消勾选。

EDIT: 既然你在评论里问了,我试着把它转换成ES5兼容的语法。我停止了使用数据属性,首先,我使用了 this 关键词,而不是 event.target (也许我不需要改变这一点,但我觉得这在以前是比较常见的)。


0
投票

默认的行为是 <input type="radio"> 是为了只允许选择其中一个输入选项。正因为如此,你的JS代码中只标记了最后一个输入。为了能够选择多个选项,使用 <input type="checkbox">.供大家参考。MDN文件.

© www.soinside.com 2019 - 2024. All rights reserved.