簡體   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