【问题标题】:push checked box values into an array using javascript使用 javascript 将复选框值推送到数组中
【发布时间】:2017-10-10 07:39:56
【问题描述】:

我有一堆复选框,每个复选框的价值都不同。如果选中该框,我创建了一个对象,该对象包含将值推送到数组中的函数。当我控制台记录空数组时,它显示为空,所以我知道它有效。我只是无法将其推送到控制台日志中。

<input type="checkbox" id="bac" value ="1">bacon - $1


var allIngredients = {

 ingredientArray: [],
 baconBox: function() {
  var bacon = document.getElementById('bac');
  if (bacon.checked === true) {
    this.ingredientArray.push(bacon.value);
  }
},

编辑:

 console.log(allIngredients.ingredientArray); 

返回一个像“[]”这样的空数组。当我选中该框时,我无法让它返回一个包含培根值的数组,就像这样“[1]”。培根的值为1。

【问题讨论】:

  • 你在任何地方调用baconBox函数吗?
  • I just cant get it to console log with the pushed value in it ...如果您想 console.log 某些内容,您需要执行 console.log(something) 的代码...您不觉得吗?
  • 正如@Cerbrus 所说,您必须在某个地方实际调用它,例如在更改复选框的事件侦听器中。
  • I created an object that holds the function to push the values into an array if the box is checked - 你已经展示了将bacon.value 推送到数组的东西......单个值,单个复选框
  • 你说它是空的,你怎么知道它有效?我在这里没有完全理解您的问题。

标签: javascript arrays object push


【解决方案1】:

正如其他人在 cmets 中指出的那样,您应该调用函数allIngredients.baconBox()

一种选择是添加一个事件侦听器,如下所示:

document.getElementById('bac').addEventListener('change', function() {
  allIngredients.baconBox();
});

虽然这种方法的缺点是取消选中该框不会从您的 allIngredients 数组中删除 bacon.value

【讨论】:

    猜你喜欢
    • 2021-09-21
    • 2018-09-04
    • 1970-01-01
    • 2018-10-07
    • 2018-07-26
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多