2013-03-25 126 views
1

我尝试添加功能以允许用户通过添加/删除/修改表及其数据来编辑表的值。为什么文本被追加几次

我设法让它做我想做的事情,但我想追加的文本会追加4次,我不明白为什么。

我已经设置了演示在这里http://jsfiddle.net/a973/CWQh9/1

,这是代码发射

$('#saveBtn').live("click", function(){ 
    var txt = $("#compName").val(); 
    var txt2 = $("#orgnr").val(); 

    $(".itms").fadeOut("normal", function() { 
      $(this).remove(); 

      $('#comp').append(txt); 
      $('#orgn').append(txt2); 
      $('#nextLast').append('<a href="#">change</a>') 
      $('#lastTd').append("<a href='#'>erase</a>"); 

    }); 

谁能帮我摆脱文本的3个额外的实例?

最终结果将仅用于演示/原型目的。

+0

尝试创建此作为的jsfiddle – 2013-03-25 16:33:45

+1

ID必须是唯一的。 – undefined 2013-03-25 16:35:19

+0

也许应该转换直播()到(),而在这种情况下,看起来像一个毫不费力的直接交换 – isherwood 2013-03-25 16:37:16

回答

1

这是因为你的每个".itms"都需要处理程序。所以每次调用append()函数。

我在下面的评论中添加了您要求的内容。

新的解决方案:Fiddle

那样做:

$('#saveBtn').live("click", function() { 
    var txt = $("#compName").val(); 
    var txt2 = $("#orgnr").val(); 
    //$('#compName, #orgnr, #saveBtn, #cncl').remove(); 

    setTimeout(function() { 
     $('#comp').append(txt); 
    $('#orgn').append(txt2); 
    $('#nextLast').append('<a href="#">change</a>') 
    $('#lastTd').append("<a href='#'>erase</a>"); 
    }, 500); 

    $(".itms").fadeOut("normal", function() { 
     $(this).remove(); 
    }); 
    $('#raden').effect("highlight", {}, 1000); 
}); 
+0

好的,你能告诉我如何防止这种情况吗? – user1425385 2013-03-25 17:09:21

+0

请参阅我的编辑。 ... – Patrick 2013-03-25 17:16:30

+0

另一个编辑... – Patrick 2013-03-25 17:22:14

1

我猜$('.itms')选择器是匹配页面上的四个元素。因此回调函数被调用四次。这意味着要追加的呼叫发生四次。

0

最有可能的原因是,有与CSS类.itms,因此回调发射四次四个元素。当我看到代码时,表中出现了四个td,因此它被触发四次

0

因为有多个元素与您的选择器匹配,所以函数被多次调用。尝试在单击元素上进行操作。

$(".itms").click().fadeOut("normal", function() { 

      $(this).remove(); 

      $('#comp').append(txt); 
      $('#orgn').append(txt2); 
      $('#nextLast').append('<a href="#">change</a>') 
      $('#lastTd').append("<a href='#'>erase</a>"); 


    }); 
1

移动的淡出通话以外,这些四行:

$('#comp').append(txt); 
$('#orgn').append(txt2); 
$('#nextLast').append('<a href="#">change</a>') 
$('#lastTd').append("<a href='#'>erase</a>"); 

所以,你得到这样的:

$('#saveBtn').live("click", function() { 
    var txt = $("#compName").val(); 
    var txt2 = $("#orgnr").val(); 
    $('#comp').append(txt); 
    $('#orgn').append(txt2); 
    $('#nextLast').append('<a href="#">change</a>') 
    $('#lastTd').append("<a href='#'>erase</a>"); 
    $(".itms").fadeOut("normal", function() { 
     $(this).remove(); 
    }); 
}) 

否则,你的追加被称为几次,每次每一次.itms

jsFiddle example(请注意,我还更新了.live().on()由于现场已被弃用。

+0

谢谢,我已经尝试过,但这使得文本追加之前项目淡出,这不是我想要的效果。基本上我只是希望输入字段消失,它们的值应该保留为保存的数据,然后用擦除和修改链接替换取消和保存按钮。 – user1425385 2013-03-25 17:04:16