Jquery不会将listener添加到新添加的字段中

Jquery doesn't add listner to a newly added field

本文关键字:添加 字段 listener Jquery 新添加      更新时间:2023-09-26

在我的页面中,我有一个add按钮,用于向表中添加新字段:

$("#add").click(function () {
 var rowCount = $('#scale tr').length + 1;
 var newRow = '<tr id="row' + rowCount + '"><td>IP:</td><td> 
              <input type="text" **class="ip"** id="ip' + rowCount + '" name="ip' + rowCount + '"> </input></td><td>Name:</td><td>  <input type="text" id="n' + rowCount + '" name="n' + rowCount + '"> </input></td><td id="ip' + rowCount + 'ave"></td><td id="add"></td><td></td></tr>';
 console.log(newRow);
 $("#scale  tr:last").after(newRow);
});

这行添加得很漂亮。

我还在文档中准备了以下函数:

$(".ip").focusout(function(){
    alert("here");
    var id =this.id;
    console.log(id);
    if(!ipcheck(id)){
        console.log("after function");
        $("#"+id).css("color","red");   
    }
    else(pinging(id));
});

每当我转到表的第一行(最初存在的一行)时,这段代码都会提醒我,但是对于新行它不起作用。我的想法是将所有的侦听器包装在一个函数中,并在任何时候发生变化时运行该函数,然而,由于我在代码中有很多这样的事情,我想知道是否有更好/更简单的方法来做到这一点。

由于您的input已被动态添加到页面中,所有事件将不可用于此元素,在这种情况下,您需要应用事件委托,以便将这些事件附加到新添加的input元素:

$("#scale  tr:last").on("focusout",".ip",function() {
     // Your code here
})