gpt4 book ai didi

javascript - 焦点事件不适用于动态内容

转载 作者:行者123 更新时间:2023-11-28 04:06:18 25 4
gpt4 key购买 nike

我正在使用 jQuery 动态添加输入。之后我尝试使用焦点事件生成另一个输入组。这是 jsfiddle ( http://jsfiddle.net/sk8UG/ )片段在下面

HTML:

    <div class='row' id='addChild'>
<input type='name' name='child0' id='child0'>
<input type='name' name='phone0' id='phone0'>
</div>

JS:

  $(document).ready(function(){
$("#child0").focus(function() {
$('#addChild').append("<input type='name' name='child1' id='child1'><input type='name' name='phone1' id='phone1'>");
});
$("#child1").focus(function() {
$('#addChild').append("<input type='name' name='child2' id='child2'><input type='name' name='phone2' id='phone2'>");
});
});

在#child0 的焦点上,它将创建#child1。但是,在#child1 的焦点上,它什么都不做

最佳答案

使用事件 delegation

$('#addChild').on("focus","#child1",function() {

// do your work here
});

注意:您必须对在运行时创建的元素使用事件委托(delegate),因为这些元素在文档就绪期间不可用

文件说

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

关于javascript - 焦点事件不适用于动态内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24823781/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com