javascript使用自定义属性添加复选框选中的值

时间:2018-03-22 02:27:23

标签: javascript

我从其他问题中找到了这个jsfiddle here。我的问题是,如何在此代码中添加自定义属性?

我试过这样但是没有工作

<input value="50" othervalue="800" type="checkbox" class="sum" data-toggle="checkbox"> Instagram

for (var i=0; i < inputs.length; i++) {
    inputs[i].onchange = function() {
        var add = $(this).attr('othervalue') * (this.checked ? 1 : -1);
        total.innerHTML = parseFloat(total.innerHTML) + add
    }
}

2 个答案:

答案 0 :(得分:1)

使用data attributes

e.g。

在输入

<input value="50" data-othervalue="800" type="checkbox" class="sum" data-toggle="checkbox">

javascript:

var add = this.dataset.othervalue * (this.checked ? 1 : -1);

答案 1 :(得分:1)

如果你真的想使用othervalue属性而不是标准的data-属性,那么就是这样:

http://jsfiddle.net/6NJ8e/272/

let totalCost = 0;
inputs.forEach(input => {
  input.onchange = function() {
    const thisInputCharge = input.value * (
      input.getAttribute('othervalue')
      ? parseInt(input.getAttribute('othervalue'))
      : 1
    );
    if (this.checked) totalCost += thisInputCharge;
    else totalCost -= thisInputCharge;
    total.textContent = totalCost;
    total1.textContent = totalCost;
  }
})

(也进行了一些其他更改 - 直接使用forEach进行迭代,在已有变量名时避免this引用,并将数据存储在变量而不是页面上的HTML)