我有一些 HTML 片段是在用户单击按钮时添加的,我想不时地对正在添加的片段进行更改。我不能使用 $(document).ready()
因为当页面准备好/加载时,代码的那些部分还不存在。
我可以在文档上使用什么来不时将函数应用于包含 future 元素的 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
事件然后执行它。事件委托(delegate)使得在动态添加的输入上监听事件成为可能:
$(document).on('input', '.class', function(){
if( $(this).val().length ){
$(this).removeClass("input-red").addClass("input-green");
} else {
$(this).addClass("input-red").removeClass("input-green");
}
});
关于javascript - 我可以在文档上使用什么来不时应用一个功能,包括 future 的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34058497/