监视动态添加的复选框上的更改事件

时间:2019-02-23 16:57:40

标签: javascript dom-events

使用以下代码在页面上特定类中包含的复选框上触发更改事件,但在我动态添加到该类的复选框上无法触发更改事件。

var Premiuminputs = document.getElementsByClassName('Premium'),
    Premiumtotal  = document.getElementById('Premium'),
    prePremiumTotal = document.getElementById('PremiumTotal');

for (var i=0; i < Premiuminputs.length; i++) {

    document.getElementsByClassName('Premium')[i].onchange = function() {

        var add = this.value * (this.checked ? 1 : -1);
        prePremiumTotal.innerHTML = Number(parseFloat(prePremiumTotal.innerHTML) + add).toFixed(2); 
        //now add shop charges via javascript and put in visible total
        var pre = parseFloat(prePremiumTotal.innerHTML);
        if((pre * .25) > 52.65){
            pre = pre + 52.65
        }else{
            pre += pre * .25;
        }
        Premiumtotal.innerHTML = Number(pre).toFixed(2);

    }
}

2 个答案:

答案 0 :(得分:1)

也许,如果您将change事件绑定到文档,然后在触发时验证target.className,就像这样:

var Premiuminputs = document.getElementsByClassName('Premium'),
    Premiumtotal = document.getElementById('Premium'),
    prePremiumTotal = document.getElementById('PremiumTotal');

document.addEventListener('change', function(event) {
    if (event.target.className == 'Premium') {
        var el = event.target,
            add = el.value * (el.checked ? 1 : -1);
        prePremiumTotal.innerHTML = Number(parseFloat(prePremiumTotal.innerHTML) + add).toFixed(2);
        //now add shop charges via javascript and put in visible total
        var pre = parseFloat(prePremiumTotal.innerHTML);
        if ((pre * .25) > 52.65) {
            pre = pre + 52.65
        } else {
            pre += pre * .25;
        }
        Premiumtotal.innerHTML = Number(pre).toFixed(2);
    }
});

尽管它是在DOM准备就绪后创建的,但它应该可以与className == 'Premium'一起在任何元素上使用。

答案 1 :(得分:0)

对于动态创建的元素,您需要将事件侦听器附加到元素。 示例: document.getElementsByClassName('Premium')[i] .addEventListener(“ change”,function(){您的代码});

var Premiuminputs = document.getElementsByClassName('Premium'),
Premiumtotal  = document.getElementById('Premium');
prePremiumTotal = document.getElementById('PremiumTotal');

for (var i=0; i < Premiuminputs.length; i++) {

document.getElementsByClassName('Premium')[i].addEventListener("change", function(){


var add = this.value * (this.checked ? 1 : -1);
prePremiumTotal.innerHTML = Number(parseFloat(prePremiumTotal.innerHTML) + add).toFixed(2); 
//now add shop charges via javascript and put in visible total
var pre = parseFloat(prePremiumTotal.innerHTML);
if((pre * .25) > 52.65){
pre = pre + 52.65
}else{
pre += pre * .25;
}
Premiumtotal.innerHTML = Number(pre).toFixed(2);

   });
}