如何将事件添加到动态元素?

时间:2014-05-14 19:04:23

标签: jquery events dynamic

我正在编写一个脚本,在单击按钮时克隆指定div的内容。该脚本将添加HTML中指定的按钮,该按钮将删除克隆的内容。我的问题是,当点击这个新按钮时,我不能简单地向该动态按钮添加一个事件功能。我目前必须在HTML中添加一个onclick属性。我想要做的不是使用onclick =" remove();",而是使用rel ="删除"然后将该事件添加到具有该rel的任何元素。

我当前的HTML:

<div id="references-content"><!-- The content to duplicate.... excludes the parent div tag i.e. only the input tag. -->
    <input type="text" name="references[]" size="30"  class="text-input" placeholder="Must contain a valid, working URL." style="position: relative;z-index: 0;">                               
</div>
<!-- Where to put the new content -->
<div id="more-references">
</div>
<div id="remove-button" style="visibility: hidden;">
     <i class="fi-x" style="cursor: pointer;padding: 10px;" onclick="removeThis(this);"></i> <!-- This element should use rel="removeThis" instead of onclick -->
</div>      
<i class="fi-plus" rel="addMore" id="references" style="cursor: pointer;"></i><!-- The button that adds content -->

My Current jQuery

$(function(){

    var i = 0;

    var oldRemove = $('#remove-button');

    $('[rel="addMore"]').on('click', function(){

        i++;

        var newRemove = oldRemove.clone();

        var buttonID = $(this).attr("id");
        var container = $('#' + buttonID + '-content');
        var content = container.html();
        var insertionPoint = $('#more-' + buttonID);

        insertionPoint.append('<div id="' + buttonID + '-' + i + '">' + content + newRemove.html() + '</div>'); 

    });

});

function removeThis(elem){

    $(elem).parent().remove();

}

我想要的jQuery似乎不起作用:

$(function(){

    var i = 0;

    var oldRemove = $('#remove-button');

    $('[rel="addMore"]').on('click', function(){

        i++;

        var newRemove = oldRemove.clone();

        var buttonID = $(this).attr("id");
        var container = $('#' + buttonID + '-content');
        var content = container.html();
        var insertionPoint = $('#more-' + buttonID);

        insertionPoint.append('<div id="' + buttonID + '-' + i + '">' + content + newRemove.html() + '</div>'); 

    });

    $('[rel="removeThis"]').on('click', function(){

        $(this).parent().remove();

    });

});

0 个答案:

没有答案