动态添加的链接不起作用

时间:2013-02-09 21:35:36

标签: jquery

我在尝试在我的脚本上触发事件(警报)时遇到问题。这是html:

<div class="dynamic-form">
    <form>
      <div class="inputs"></div>
      <a href="#" id="add">ADD</a>
      <input name="submit" type="button" class="submit" value="Submit">
    </form>
</div>

和JS:

$(document).ready(function(){

    var i = 1;

    $('#add').click(function() {
        $('<div id="d' + i + '" class="fielddiv"><input type="text" class="field" name="dynamic[]" value="' + i + '" /><a href="#" id="remove_question">Cancella</a><hr></div>').fadeIn('slow').appendTo('.inputs');
        i++;
    });

    $('#remove_question').on("click", function(event) {
        alert('dsfsfd');
        //$('#d' + $this.attr('todel')).remove();
    });


    // here's our click function for when the forms submitted

    $('.submit').click(function(){

        var answers = [];
        $.each($('.field'), function() {
            answers.push($(this).val());
        });

        if(answers.length == 0) {
            answers = "none";
        }  

        alert(answers);

        return false;                     
    });

});

关于点击功能的删除问题应该触发警报但没有做任何事情,甚至没有错误,我做错了什么?这也是jsfiddle

2 个答案:

答案 0 :(得分:2)

您必须具有委派语法。此外,使用CLASSES NOT ID或您将拥有重复的ID。

工作JSfiddle:

http://jsfiddle.net/Z6x8X/2/

代码:

$(document).ready(function(){

    var i = 1;

    $('#add').click(function() {
        $('<div id="d' + i + '" class="fielddiv"><input type="text" class="field" name="dynamic[]" value="' + i + '" /><a href="#" class="remove_question">Cancella</a><hr></div>').fadeIn('slow').appendTo('.inputs');
        i++;
    });

    $(document).on("click", ".remove_question", function(event) {
        alert('dsfsfd');
        //$('#d' + $this.attr('todel')).remove();
    });


    // here's our click function for when the forms submitted

    $('.submit').click(function(){

    var answers = [];
    $.each($('.field'), function() {
        answers.push($(this).val());
    });

    if(answers.length == 0) {
        answers = "none";
    }  

    alert(answers);

    return false;

    });


});

答案 1 :(得分:0)

对于动态添加的元素,您需要委派的事件处理程序:

$(document).on('click', '#remove_question', function(event) {
    alert('dsfsfd');
});

此外,使用您的代码,可以添加具有相同ID的无限数量的锚点,这也不会起作用,因为ID应该是唯一的。

相关问题