猿问

如何将值从一个函数传递到另一个函数

 var boxes = document.getElementsByName('toggle');


  function markPreceding() {

    var curIndex = null;

    for (var j = 0; j < boxes.length; j++) {

      if (boxes[j].checked) {

        curIndex = j;

      }

    }

  }


  function checkInputs() {

    for (var k = 0; k <= curIndex.length; k++) {

      boxes[k].checked = true;

    }

  }


  for (var i = 0; i <= boxes.length; i++) {

    boxes[i].onchange = markPreceding;

    boxes[i].onchange = checkInputs;

  }

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

在将此“库索引”值传递到检查输入函数时遇到问题。这应该在检查输入之前检查输入,并获取其值来执行此操作。

此项目只需要 ES5 合成器。


慕工程0101907
浏览 114回答 1
1回答

Cats萌萌

编辑:ES5 语法方式const boxes = document.getElementsByName('toggle');boxes.forEach(function(box, I) {&nbsp; box.onclick = function(e) {&nbsp; &nbsp; markPreceding(i);&nbsp; };});function markPreceding(i) {&nbsp; for (var j = 0; j < boxes.length; j++) {&nbsp; &nbsp; if(j <= i) {&nbsp; &nbsp; &nbsp; document.getElementById('product-' + (j + 1)).checked = true;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; document.getElementById('product-' + (j + 1)).checked = false;&nbsp; &nbsp; }&nbsp; }}源语言:尝试使用这个:const boxes = document.getElementsByName('toggle');boxes.forEach((box, i) => {&nbsp; box.onclick = (e) => {&nbsp; &nbsp; markPreceding(i);&nbsp; };});function markPreceding(i) {&nbsp; for (var j = 0; j < boxes.length; j++) {&nbsp; &nbsp; if(j <= i) {&nbsp; &nbsp; &nbsp; document.getElementById(`product-${j + 1}`).checked = true;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; document.getElementById(`product-${j + 1}`).checked = false;&nbsp; &nbsp; }&nbsp; }}由于某种原因,通过 返回的数组更新输入似乎存在问题。不知道为什么,但此代码已经过验证。请参阅此处的工作示例。NodeListdocument.getElementsByName
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答