【问题标题】:Loop on ID and each function循环 ID 和每个函数
【发布时间】:2011-03-27 17:55:07
【问题描述】:

我使用 JQUERY EACH 函数对 12 个文本框值进行动态求和,并使用此代码使用“txt”类:

<script>
    $(document).ready(function(){

        //iterate through each textboxes and add keyup
        //handler to trigger sum event
        $(".txt").each(function() {

            $(this).keyup(function(){
                calculateSum();
            });
        });

    });

    function calculateSum() {

        var sum = 0;
        //iterate through each textboxes and add the values
        $(".txt").each(function() {

            //add only if the value is number
            if(!isNaN(this.value) && this.value.length!=0) {
                sum += parseFloat(this.value);
                }

        });

        $("#sum").html(sum);
</script>

我想创建 4 个仅使用 3 个文本框值动态计算的小计。我在表格中为每个人添加了 4 个不同的 ID。我如何使用上面的函数来动态计算当前 id 的小计。得到结果的 spans id 命名为“ID_SUM”(ID 必须是动态的,根据修改的文本框的 ID 值)?? 非常感谢。

【问题讨论】:

  • 您也可以发布 HTML 吗?而且你不需要遍历所有元素来附加事件处理程序,$(".txt").keyup(function(){calculateSum();}); 会做同样的事情。

标签: jquery each


【解决方案1】:

我找到了解决方案... ID 是唯一的,所以它不起作用。我使用了这样的名称属性:

<script>
    $(document).ready(function(){

        //iterate through each textboxes and add keyup
        //handler to trigger sum event
        $(".txt").each(function() {

            $(this).keyup(function(){
            calculateSum($(this).attr("name"));
            });
        });

    });

    function calculateSum(groupe) {

        var sum = 0;
        var subtotal = 0
        //iterate through each textboxes and add the values
        $(".txt").each(function() {

            //add only if the value is number
            if(!isNaN(this.value) && this.value.length!=0) {
                sum += parseFloat(this.value);
                }

        });
        //.toFixed() method will roundoff the final sum to 2 decimal places : $("#sum").html(sum.toFixed(2))
        $("#sum").html(sum);

        $('input[name="' + groupe + '"]').each(function() {

            //add only if the value is number
            if(!isNaN(this.value) && this.value.length!=0) {
                subtotal += parseFloat(this.value);
                }

        });
        //.toFixed() method will roundoff the final sum to 2 decimal places : $("#sum").html(sum.toFixed(2))
        $("#" + groupe + "_SUM").html(subtotal);

    }
</script>

【讨论】:

    猜你喜欢
    • 2016-12-21
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 2013-04-09
    • 2021-01-02
    相关资源
    最近更新 更多