0

我的函数可能使用过时的 jquery 元素。例如,当我使用 close 和回调时:

    $("input").each(function () {
       var input = $(this);

       //here for example we remove input from DOM
       //and insert the new one input

       $.ajax(url, function(){
          fun(input)
       }
    });

function fun(input){
//do something
input.val('newValue')
}

问题是:我如何确定对变量的引用仍然正确。如果元素已被重新创建,我如何获得新输入的新参考(输入没有 id 和类)?

UPDATE1:我做了小更新。我们在函数fun中使用旧的输入引用。并且newValue将不适用于新输入,因为当前输入是旧值。

4

1 回答 1

1

您可以通过检查 jQuery 对象的长度来检查元素是否存在。例如:

if($(this).length < 1)
{
    // the element no longer exists in the DOM
}

但是,您可以使用 jQuery 的on()函数将事件绑定到现在或将来存在的元素,这可能是一种比您当前使用的方法更好的方法。例如:

$('body').on('click', 'input', function(e) {  
    // Place your click handler here.
});

这篇文章可能对你来说是值得一读的。

于 2013-04-25T09:33:01.240 回答