动态生成字段的Jquery递增和递减

时间:2012-04-23 17:24:16

标签: javascript jquery jquery-mobile

我很简单 code 增加和减少字段。一切都很好,但我不知道我得到了多少字段(由mvc生成)我的问题是如何为页面上的每个字段智能绑定两个按钮? 我试图使用$(this.id+"x").val(currentVal - 1),但我认为这是错误的方式。

感谢您的任何建议

其他:

  1. 我无法使用Jquery Mobile范围输入。
  2. 文本框“Text Pin#4”必须始终关注。
  3. 所有按钮都必须可以点击移动设备。

2 个答案:

答案 0 :(得分:1)

您可以选择与触发事件的元素相关的元素:

$(".bplus").click(function() {

    //find the input relative to this element
    $(this).closest('td').prev().children('input').val(function (i, oldValue) {

        //make sure the old value is being interpreted as an integer
        oldValue = parseInt(oldValue, 10);

        //if the old value is a valid integer below 999 then add one,
        //otherwise return 999
        return (oldValue != NaN && oldValue < 999) ? (oldValue + 1) : 999;
    });
});

$(".bminus").click(function() {

    //find the input relative to this element
    $(this).closest('td').next().children('input').val(function (i, oldValue) {

        //make sure the old value is being interpreted as an integer
        oldValue = parseInt(oldValue, 10);

        //if the old value is a valid integer above 0 then subtract one,
        //otherwise return 0
        return (oldValue != NaN && oldValue > 0) ? (oldValue - 1) : 0;
    });
});

以下是演示:http://jsfiddle.net/uSzr7/16/

以下是ya的一些文档:

处理验证的另一种方法是始终添加或减去一个,但随后向change元素添加input事件处理程序,以检查该值是否有效。这有助于使用本机表单控件,因为您使用的是type="number"输入标记。

答案 1 :(得分:0)

$(".bplus").click(function(){
    var txtField = $(this).parents('tr').find('input[type="number"]')
    var currentVal = parseInt(txt.val());
    if (currentVal < 999)
        txtField.val((currentVal || 0) + 1);
});

我放(currentVal || 0),这意味着如果currentVal==NaN,它将被0替换