我可以在文档上使用什么来不时应用函数,包括未来元素

What can I use on the document to apply a function from time to time including future elements?

本文关键字:函数 应用 包括 元素 未来 文档 什么 我可以      更新时间:2023-09-26

我有一些HTML片段是在用户单击按钮时添加的,我希望不时对添加的片段进行更改。我不能使用$(document).ready(),因为当页面准备好/加载时,代码的这些部分还没有出现。

我可以在文档上使用什么来不时地将函数应用到DOM(包括未来的元素)?类似于:

$(document).atEach(3000, function() {
    // As the user clicks a button, a field is added to the page with a class.
    // The "window" applies every 3 seconds the given function within the scope of all the DOM,
    // (It updates the elements that were inserted)
    if ($(".class").val().length) {
        $(".class").removeClass("input-red").addClass("input-green");
    } else {
        $(".class").addClass("input-red").removeClass("input-green");
    }
});

要以规则的时间间隔执行函数,可以使用setInteval

setInterval(function() {
    // As the user clicks a button, a field is added to the page with a class.
    // The "window" applies every 3 seconds the given function within the scope of all the DOM,
    // (It updates the elements that were inserted)
    if ($(".class").val().length) {
        $(".class").removeClass("input-red").addClass("input-green");
    } else {
        $(".class").addClass("input-red").removeClass("input-green");
    }
}, 3000);

http://jsfiddle.net/ma7p3hcr/1/

我不确定你的函数应该做什么,但我想这是某种输入验证。如果是这种情况,那么您应该只监听oninput事件并执行它。事件委派使在动态添加的输入上侦听事件成为可能:

$(document).on('input', '.class', function(){
   if( $(this).val().length ){
        $(this).removeClass("input-red").addClass("input-green");
    } else {
        $(this).addClass("input-red").removeClass("input-green");
    }
});

http://jsfiddle.net/tnc84mhf/