简体   繁体   English

如何将值从一个 function 传递到另一个

[英]How to pass a value from one function to another

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

Have a problem passing this "curIndex" value to checkInputs function.将此“curIndex”值传递给 checkInputs function 时遇到问题。 This should check inputs before checked input and get its value to do it.这应该在检查输入之前检查输入并获取其值来执行此操作。

Only ES5 synthax needed for this project.这个项目只需要 ES5 合成器。

EDIT: The ES5 Syntax way编辑:ES5 语法方式

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

boxes.forEach(function(box, I) {
  box.onclick = function(e) {
    markPreceding(i);
  };
});

function markPreceding(i) {
  for (var j = 0; j < boxes.length; j++) {
    if(j <= i) {
      document.getElementById('product-' + (j + 1)).checked = true;
    } else {
      document.getElementById('product-' + (j + 1)).checked = false;
    }
  }
}

ORIGINAL:原来的:

Try using this:尝试使用这个:

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

boxes.forEach((box, i) => {
  box.onclick = (e) => {
    markPreceding(i);
  };
});

function markPreceding(i) {
  for (var j = 0; j < boxes.length; j++) {
    if(j <= i) {
      document.getElementById(`product-${j + 1}`).checked = true;
    } else {
      document.getElementById(`product-${j + 1}`).checked = false;
    }
  }
}

For some reason, there seems to be an issue with updating the inputs through the NodeList array returned by document.getElementsByName .出于某种原因,通过document.getElementsByName返回的NodeList数组更新输入似乎存在问题。 Not sure why, but this code has been verified.不知道为什么,但这个代码已经过验证。 See working example here .请参阅此处的工作示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM