如何在Ajax加载后选择元素

How to select element after Ajax Load?

本文关键字:选择 元素 加载 Ajax      更新时间:2023-09-26

我的html中有输入:

<input type="text" id="1" value="1" name="1">
<input type="text" id="2" value="2" name="2">

然后我使用ajax加载另一个输入:

<input type="text" id="3" value="3" name="3">

有一个javascript文件,代码:

$('input[type=text]').focusin(function() {
    var Id = this.id;
    someActionWithId(Id);
}).focusout(function(){
    var Id = this.id;
    someActionWithId(Id);
});

谁能告诉我为什么我不能选择由AJAX加载的输入。也许有人能提出解决办法?谢谢。

您需要像这样为动态加载的元素绑定事件:

$(document).on('focusin','input[type=text]',function() {
    var Id = this.id;
    someActionWithId(Id);
});
$(document).on('focusout','input[type=text]',function(){
    var Id = this.id;
    someActionWithId(Id);
});