使用 jquery 增加和减少输入的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19129804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:15:09  来源:igfitidea点击:

Increase and decrease values for inputs using jquery

javascriptjquery

提问by Faizal

I need to increase and decrease the value of inputs when clicking the + and - buttons but it doesn't seem to work. I got the code from this post: How to increase the value of a quantity field with jQuery?When clicking on the add button, I inserted a console.log statement for debugging purposes and surprisingly, I get a value of 3 even though I clicked on a button with an id of add1. Would really appreciate it if you could point out to me the error, thanks!

单击 + 和 - 按钮时,我需要增加和减少输入的值,但它似乎不起作用。我从这篇文章中得到了代码:如何使用 jQuery 增加数量字段的值?当单击添加按钮时,我插入了一个用于调试目的的 console.log 语句,令人惊讶的是,即使我单击了一个 ID 为 add1 的按钮,我也得到了 3 的值。如果您能指出错误,我将不胜感激,谢谢!

HTML:

HTML:

<body>
    <p>
        <img src="http://i.imgur.com/yOadS1c.png" id="minus1" width="20" height="20">
        <input id="qty1" type="text" value="1">
        <img id="add1" src="http://i.imgur.com/98cvZnj.png" width="20" height="20">
    </p>

    <p>
        <img src="http://i.imgur.com/yOadS1c.png" id="minus2" width="20" height="20">
        <input id="qty2" type="text" value="1">
        <img id="add2" src="http://i.imgur.com/98cvZnj.png" width="20" height="20">
    </p>
</body>

jQuery:

jQuery:

$(function () {
    var numButtons = 2;
    //console.log(typeof(numButtons));
    //console.log(numButtons);
    for (var i = 1; i <= numButtons; i++) {

        $("#add" + i).click(function () {
            console.log(i);
            var currentVal = parseInt($("#qty" + i).val());
            //console.log(currentVal);
            if (!isNaN(currentVal)) {
                $("#qty" + i).val(currentVal + 1);
            }
        });

        $("#minus" + i).click(function () {
            var currentVal = parseInt($("#qty" + i).val());
            if (!isNaN(currentVal) && currentVal > 0) {
                $("#qty" + i).val(currentVal - 1);
            }
        });
    }
});

jsfiddle - http://jsfiddle.net/hMS6Y/

jsfiddle - http://jsfiddle.net/hMS6Y/

回答by Rohan Kumar

Try this in a simple way using class,

以简单的方式尝试使用class,

HTML

HTML

<body>
    <p>
        <img src="http://i.imgur.com/yOadS1c.png" id="minus1" width="20" height="20" class="minus"/>
        <input id="qty1" type="text" value="1" class="qty"/>
            <img id="add1" src="http://i.imgur.com/98cvZnj.png" width="20" height="20" class="add"/>
    </p>
    <p>
        <img src="http://i.imgur.com/yOadS1c.png" id="minus2" width="20" height="20" class="minus"/>
        <input id="qty2" type="text" value="1" class="qty"/>
        <img id="add2" src="http://i.imgur.com/98cvZnj.png" width="20" height="20" class="add"/>
    </p>
</body>

SCRIPT

脚本

$(function () {
    $('.add').on('click',function(){
        var $qty=$(this).closest('p').find('.qty');
        var currentVal = parseInt($qty.val());
        if (!isNaN(currentVal)) {
            $qty.val(currentVal + 1);
        }
    });
    $('.minus').on('click',function(){
        var $qty=$(this).closest('p').find('.qty');
        var currentVal = parseInt($qty.val());
        if (!isNaN(currentVal) && currentVal > 0) {
            $qty.val(currentVal - 1);
        }
    });
});

Fiddle:http://jsfiddle.net/hMS6Y/2/

小提琴:http : //jsfiddle.net/hMS6Y/2/

Alternatively,you can short your code like,

或者,您可以缩短代码,例如,

$(function() {
  $('.minus,.add').on('click', function() {
    var $qty = $(this).closest('p').find('.qty'),
      currentVal = parseInt($qty.val()),
      isAdd = $(this).hasClass('add');
    !isNaN(currentVal) && $qty.val(
      isAdd ? ++currentVal : (currentVal > 0 ? --currentVal : currentVal)
    );
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<p>
  <img src="http://i.imgur.com/yOadS1c.png" id="minus1" width="20" height="20" class="minus" />
  <input id="qty1" type="text" value="1" class="qty" />
  <img id="add1" src="http://i.imgur.com/98cvZnj.png" width="20" height="20" class="add" />
</p>
<p>
  <img src="http://i.imgur.com/yOadS1c.png" id="minus2" width="20" height="20" class="minus" />
  <input id="qty2" type="text" value="1" class="qty" />
  <img id="add2" src="http://i.imgur.com/98cvZnj.png" width="20" height="20" class="add" />
</p>

回答by Gary.S

The issue at hand is that the value of iis 3by the time the loop ends. What you want to do is save the value of each iteration so that when the clickevent fires it will still hold the correct value (the value at the time of the event being wired up). One way to do this is with what are called closures. Closures basically close around the value and save the function call with the value used to be called later. One way to accomplish this is with a function factory.

眼下的问题是,价值i3由当时的循环结束。您想要做的是保存每次迭代的值,以便在click事件触发时它仍将保持正确的值(事件连接时的值)。一种方法是使用所谓的闭包。闭包基本上关闭了值,并将函数调用保存在以后调用的值中。实现此目的的一种方法是使用函数工厂。

function add(value){
    console.log(value);
    var currentVal = parseInt($("#qty" + value).val());    
    if (!isNaN(currentVal)) {
        $("#qty" + value).val(currentVal + 1);
    }
};

function addClosure(value){
    return function(){
        add(value);
    };
};

At this point all you need to do is change the click event as follows:

此时你需要做的就是改变点击事件如下:

$("#add" + i).click(addClosure(i));

JSFiddle: http://jsfiddle.net/infiniteloops/y9huk/

JSFiddle:http: //jsfiddle.net/infiniteloops/y9huk/

MDN Closures: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

MDN 闭包:https: //developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures

回答by Jay Bhatt

Working code.

工作代码。

<body>
    <div id='placeholder'>
    <p>
        <img src="http://i.imgur.com/yOadS1c.png" act='min' id="1" width="20" height="20" />
        <input id="qty1" type="text" value="1">
        <img src="http://i.imgur.com/98cvZnj.png" act='add' id="1" width="20" height="20" />
    </p>
    <p>
        <img src="http://i.imgur.com/yOadS1c.png" act='min' id="2" width="20" height="20" />
        <input id="qty2" type="text" value="1">
        <img src="http://i.imgur.com/98cvZnj.png" act='add' id="2" width="20" height="20" />
    </p>
    </div>
</body>



$(function () {
        $('#placeholder img').each(function(){
            $(this).click(function(){

            $action = $(this).attr('act');        
            $id = $(this).attr('id');
            $val = parseInt($('#qty'+$id).val());

            if($action == 'add'){
                $val = $val + 1;
            } else {
                if($val > 0){
                    $val = $val - 1;    
                }
            }
            $('#qty'+$id).val($val);

            });

        });
    });

回答by MRRaja

<div class="box-qty">
<a href="javascript:void(0);" class="quantity-minus">-</a>
<input type="text" name="p_quantity" id="qnt" class="quantity" value="1">
<a href="javascript:void(0);" class="quantity-plus">+</a>
</div>

<script>
$(".quantity-plus").click(function(){     
 $("#qnt").val(Number($("#qnt").val())+1);
});

$(".quantity-minus").click(function(){
 if($("#qnt").val()>1)
 $("#qnt").val(Number($("#qnt").val())-1);     
});
<script>

回答by Ritesh

Your variable i is global in the case it will actually work for #add3, #minus3. Here in code you can try this thing-

您的变量 i 是全局变量,因为它实际上适用于 #add3、#minus3。在代码中,您可以尝试此操作-

$(function () {
    var numButtons = 2;
    //console.log(typeof(numButtons));
    //console.log(numButtons);
    for (var i = 1; i <= numButtons; i++) {
        var t = i; //Now t is local 
        $("#add" + t).click(function () {
            console.log(t);
            var currentVal = parseInt($("#qty" + t).val());
            //console.log(currentVal);
            if (!isNaN(currentVal)) {
                $("#qty" + t).val(currentVal + 1);
            }
        });

        $("#minus" + t).click(function () {
            var currentVal = parseInt($("#qty" + t).val());
            if (!isNaN(currentVal) && currentVal > 0) {
                $("#qty" + t).val(currentVal - 1);
            }
        });
    }
});

Hope this will help.

希望这会有所帮助。

回答by Pragnesh Chauhan

in for loop ivalue become 3

在 for 循环i值变为3

DEMO

演示

$(function () {

    $("#add1").click(function () {
            add(1);
    });

    $("#minus1").click(function () {
        minus(1);
    });

$("#add2").click(function () {
            add(2);
    });

    $("#minus2").click(function () {
        minus(2);
    });
});

function add(i){
var currentVal = parseInt($("#qty" + i).val());

        if (!isNaN(currentVal)) {
            $("#qty" + i).val(currentVal + 1);
        }
}

function minus(i){
  var currentVal = parseInt($("#qty" + i).val());
        if (!isNaN(currentVal) && currentVal > 0) {
            $("#qty" + i).val(currentVal - 1);
        }
}