2015-12-03 60 views
1

我有一些随用户点击按钮而添加的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"); 
    } 
}); 

回答

2

要在固定的时间间隔执行功能,您可以使用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/

+0

哦,我明白了!我只需要在“全局范围”上使用setInterval()。非常感谢你! –

+1

@EricsonWillians'setInterval'回答你的问题,但另一种方法可能解决潜在的问题;) – pawel