使用 jQuery 添加多个动态值并输出结果

Adding multiple dynamic values with jQuery and outputting results

本文关键字:输出 结果 动态 jQuery 添加 使用      更新时间:2023-09-26

所以我的问题是我正在尝试从不同的框中添加一堆数字,这些数字会根据它们的下拉列表而变化,下拉位现在都很好,我无法:(添加结果!

这是我到目前为止的尝试:

<select id=discount[0] name=discount[0]>
    <option value=1>option 1</option>
    <option value=2>option 2</option>
</select>
<input class=prices type=text id=postdiscount[0] value=1>
<select id=discount[1] name=discount[1]>
    <option value=1>option 1</option>
    <option value=2>option 2</option>
</select>
<input class=prices type=text id=postdiscount[1] value=2>
    <br>
        total: <div id=netpricestotal></div>

和JS:

var netprice = 0;
$("#discount''[0'']").change(function () {
    $("#postdiscount''[0'']").val(this.value);
    $(".prices").each(function(index, obj){
            netprice += index.value;
    });
    $("#netpricestotal").text(netprice);
});
$("#discount''[1'']").change(function () {
    $("#postdiscount''[1'']").val(this.value);
    $(".prices").each(function(index, obj){
            netprice += index.value;
    });
    $("#netpricestotal").text(netprice);
});

JSFIDDLE:

http://jsfiddle.net/t75ut97f/12/

谢谢!

编辑:

谢谢大家,设法用 Number() (http://jsfiddle.net/t75ut97f/16/) 自己修复了它,还看到了使用 parseint 的替代方法的接受答案。

你没有任何

元素与类 netprices ,你的意思是prices(输入)。此外,您需要parseInt()值才能将其转换为数字。

将 var netprice移动到事件change以重置它。

看到它在这里工作。

$("#discount''[0'']").change(function () {
    var netprice = 0;
    $("#postdiscount''[0'']").val(this.value);
    $(".prices").each(function (index, obj) {
        netprice += parseInt($(this).val());
    });
    $("#netpricestotal").text(netprice);
});
$("#discount''[1'']").change(function () {
    var netprice = 0;
    $("#postdiscount''[1'']").val(this.value);
    $(".prices").each(function (index, obj) {
        netprice += parseInt($(this).val());
    });
    $("#netpricestotal").text(netprice);
});

我希望链式jQuery插件能满足你的需求