如何处理通过jQuery插入的标记上的事件

时间:2017-03-29 15:15:44

标签: javascript jquery html

我有以下标记:

<div id="section">
    <input type="text" id="myInput">
</div>

点击按钮,我正在使用此脚本克隆并插入带有唯一ID的此标记的副本:

var newSection = $("#section").clone();
$(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
$(newSection).find("input").attr('id', "myInput" + ($("input[id^=myInput").length + 1));
$("div[id^=section").last().after(newSection);

我的结果标记:

<div id="section">
    <input type="text" id="myInput">
</div>
<div id="section2">
    <input type="text" id="myInput2">
</div>

我的问题:是否可以使用jQuery操作这个新标记?我假设因为它在点击后动态加载它不是初始DOM的一部分并且jQuery不识别它?我无法在#myInput2上注册点击事件。感谢您的任何见解。

2 个答案:

答案 0 :(得分:0)

如果将它们包装在容器中,则可以委派该容器跟踪按钮。例如,如果您有:

<div id="container">
    <div id="section">
        <input type="text" id="myInput">
    </div>
    <div id="section2">
        <input type="text" id="myInput2">
    </div>
</div>

您可以将任务委托给容器,如下所示:

$("#container").on("click","input",function(){
    var newSection = $("#section").clone();
    $(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
    $(newSection).find("input").attr('id', "myInput" + 
    ($("input[id^=myInput").length + 1));
    $("div[id^=section").last().after(newSection);
}

这样,如果未在绑定时定义,则可以操作它们

编辑:已从.delegate()更新为.on()

答案 1 :(得分:0)

在您的标记中添加类:

<div id="section" class="section">
    <input type="text" id="myInput" class="section-input">
</div>

简化您的代码

var $newSection = $('#section').clone();
var $sections = $('.section');
var index = $sections.length +1;
$newSection.attr('id', 'section' + index);
$newSection.find('input').attr('id', 'myInput' + index);

$sections.last().after($newSection);

确保将点击处理程序添加到现有元素和新元素

$(document).on('click', '.section-input', function(){
    ... your code
})