简体   繁体   English

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

[英]How to handle events on markup inserted through jQuery

I have the following markup: 我有以下标记:

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

On click of a button, I'm cloning and inserting a copy of this markup with unique IDs using this script: 单击按钮后,我正在使用以下脚本克隆并插入具有唯一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);

My resulting markup: 我产生的标记:

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

My question: is it possible to manipulate this new markup with jQuery? 我的问题:是否可以使用jQuery操作此新标记? I assume since it has loaded dynamically after a click it's not part of the initial DOM and jQuery doesn't recognize it? 我认为由于单击后它已经动态加载,因此它不是初始DOM的一部分,而jQuery无法识别它? I'm having trouble getting a click event to register on #myInput2 . 我在获取点击事件以在#myInput2上注册时遇到麻烦。 Thanks for any insight. 感谢您的任何见解。

if you wrap them in a container, you can delegate that container keep track of the buttons. 如果将它们包装在容器中,则可以委托该容器跟踪按钮。 For example, if you have: 例如,如果您有:

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

you can delegate the task to the container like this: 您可以将任务委托给容器,如下所示:

$("#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);
}

This way you can manipulate them if not defined while binding 这样,如果绑定时未定义它们,则可以对其进行操作

EDIT : Updated from .delegate() to .on() 编辑 :从.delegate()更新为.on()

Add classes to your markup: 将类添加到您的标记中:

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

Simplify your code 简化您的代码

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);

Make sure click handlers are added to existing and new elements 确保将点击处理程序添加到现有元素和新元素中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM