为什么文本被多次附加

时间:2013-03-25 16:32:09

标签: jquery html

我尝试添加功能以允许用户编辑表的值,方法是添加/删除/修改表及其数据。

我已经设法让它做我想要的但是我要附加的文字被附加了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个额外的文本实例吗?

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

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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);
});

答案 2 :(得分:1)

将这四行移到fadeOut调用之外:

$('#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(),因为已弃用直播。

答案 3 :(得分:0)

最可能的原因是css类.itms有四个元素,因此回调被触发了四次。在我看到代码时,表中有四个td,因此会被触发四次

答案 4 :(得分: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>");


    });