【问题标题】:plus minus button with specific parent input doesn't work带有特定父输入的加减号按钮不起作用
【发布时间】:2014-03-19 17:52:41
【问题描述】:

你可以在这里看到jsfiddle.net/TTU4Z/1/ 有问题的 jquery 代码在下面,如果我在没有我所有代码的情况下运行它(如在 jsfiddle 中),它运行完美。但是我的所有代码都没有运行。

$(document).ready(function() {

// This button will increment the value
$('.plus').click(function(e){
    // Stop acting like a button
    e.preventDefault();
    // Get the field name
    fieldName = $(this).attr('field');
    // Get its current value
    var currentVal = parseInt($('input[id='+fieldName+']').val());
    // If is not undefined
    if (!isNaN(currentVal)) {
        // Increment
        $('input[id='+fieldName+']').val(currentVal + 1);
    } else {
        // Otherwise put a 0 there
        $('input[id='+fieldName+']').val(0);
    }
});
// This button will decrement the value till 1
$(".minus").click(function(e) {
    // Stop acting like a button
    e.preventDefault();
    // Get the field name
    fieldName = $(this).attr('field');
    // Get its current value
    var currentVal = parseInt($('input[id='+fieldName+']').val());
    // If it isn't undefined or its greater than 0
    if (!isNaN(currentVal) && currentVal > 0) {
        // Decrement one
        $('input[id='+fieldName+']').val(currentVal - 1);
    } else {
        // Otherwise put a 0 there
        $('input[id='+fieldName+']').val(0);
    }
});

});

单击“添加”按钮一切都很好,但是当您单击减号或加号按钮之一时,它会全部删除。

如您所见,它应该增加或减少相对输入的 val,但如果我尝试编辑这些函数中的所有内容,则没有任何变化。 怎么办?

【问题讨论】:

  • 那是很多重复的代码。您应该为两者使用一个函数,通过data-* 属性或hasClass() 检查传递是否应该添加或减去。此外,field 不是有效的 HTML 属性:您应该改用 data-field

标签: javascript jquery html css increment


【解决方案1】:

由于您是动态添加元素,因此在这种情况下您必须使用event delegation。实际上,注册的事件并没有在您的上下文中调用,这就是 buttons 展示其原始行为的原因。

试试,

$(document).on('click','.plus',function(e){

$(document).on('click','.minus',function(e){

此外,您动态构建的selector 包含一些meta-characters,只需将其作为string 传递,或者您必须将其传递给escape,以使您的代码正常工作。

DEMO


修复连接问题后的新演示。在那个演示中,我只是删除了[id='blah'] 之类的属性选择器,并将其替换为$('#blah')

DEMO - I

【讨论】:

  • 嘿伙计,由于我在回答中指出的错误,您的代码不允许您更改多个元素。
  • @MichaelCoxon 实际上我认为 OP 是故意这样做的,这就是为什么我刚刚给出了解决元字符问题的解决方案。
  • 我认为这可能是因为它从来没有工作过 OP 从来没有看到这个问题。修好你的小提琴,我会+1 :)
  • @MichaelCoxon 我已经更新了帖子,但你应该为指出这个问题而点赞。 :) +1
【解决方案2】:

查看更新的小提琴http://jsfiddle.net/LfNmh/

您的 x 变量位于代码字符串中,它应该在代码中。第 15 行 ..

var numPortata = '<td><button class="minus" field="portata'+x+'">-</button><input id="portata'+x+'" type="number" name="numPortata[]" value="1" size="10" min="1" max="10" step="1" required><button class="plus" field="portata'+x+'">+</button></td>';

我还更改了代码,以便按照 Rajaprabhu 所说,将事件附加到文档级别。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多