JavaScript事件侦听器运行两次

时间:2014-09-24 15:21:34

标签: javascript jquery events listener

作为参考,请参阅下面JSFiddle中的我的示例。每次有人点击加号按钮时,都应在下面插入一个新行。除了插入的新行数量始终是当前现有行数量的两倍之外,这种方法很好。我怎样才能避免这种奇怪的行为,或者是什么原因呢?请单击第一行按钮以查看问题。

http://jsfiddle.net/jrxeua6L/

var answers = [{
    order: 1,
    content: "placeholder"
}],
    appendAnswer = function() {

    answers.push({
        order: answers.length + 1,
        content: $(this).parent().prev().val()
    });

    $("#answers").empty();

    $.each(answers, function(key, value) {
        $("#answers").append('<div class="input-group"><input type="text" class="form-control" placeholder="Enter your answer"><span class="input-group-btn"><button type="button" class="btn btn-default" title="Add a question" data-action="add"><span class="glyphicon glyphicon-plus"></span></button><button type="button" class="btn btn-default" title="Delete this question" data-action="delete" disabled><span class="glyphicon glyphicon-trash"></span></button></span></div>');

        $("#answers button[data-action='add']").one("click", appendAnswer);
    });
};

$("#answers button[data-action='add']").one("click", appendAnswer);

3 个答案:

答案 0 :(得分:2)

使用事件委派

$("#answers").on("click", "button[data-action='add']",appendAnswer);

问题的原因是你在每个循环中的相同元素上绑定多个事件,所以删除那里的委托。

.each()循环

中删除此行
$("#answers button[data-action='add']").one("click", appendAnswer);

DEMO

答案 1 :(得分:0)

这是一个有效的解决方案http://jsfiddle.net/jrxeua6L/4/

var answers = [{
            order: 1,
            content: "placeholder"
        }],
            appendAnswer = function() {

            answers.push({
                order: answers.length + 1,
                content: $(this).parent().prev().val()
            });

            $("#answers").empty();

            $.each(answers, function(key, value) {
                $("#answers").append('<div class="input-group"><input type="text" class="form-control" placeholder="Enter your answer"><span class="input-group-btn"><button type="button" class="btn btn-default" title="Add a question" data-action="add"><span class="glyphicon glyphicon-plus"></span></button><button type="button" class="btn btn-default" title="Delete this question" data-action="delete" disabled><span class="glyphicon glyphicon-trash"></span></button></span></div>');

                //$("#answers button[data-action='add']").on("click", appendAnswer);
            });
        };

        $('body').on("click", "#answers button[data-action='add']", appendAnswer);

答案 2 :(得分:-1)

更改此行:

$("#answers button[data-action='add']").one("click", appendAnswer);

对此:

$("#answers button[data-action='add']").off("click").one("click", appendAnswer);