繁体   English   中英

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

[英]javascript add checkbox-checked values with the use of custom attribute

我从其他问题中找到了这个现有的jsfiddle 我的问题是,如何在此代码中放入自定义属性?

我已经尝试过了,但是没有用

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

使用数据属性

例如

在输入上

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

JavaScript:

var add = this.dataset.othervalue * (this.checked ? 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将数据存储在一个变量,而在页面上)

暂无
暂无

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

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