javascript - 我可以在文档上使用什么来不时应用一个功能,包括 future 的元素?

标签 javascript jquery

我有一些 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");
    }
});

http://jsfiddle.net/tnc84mhf/

关于javascript - 我可以在文档上使用什么来不时应用一个功能,包括 future 的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34058497/

相关文章:

javascript - AJAX 调用在 JavaScript 中运行 PHP 脚本

javascript - JQuery 在表格末尾追加数据

javascript - 方向为 rtl 时的 jQuery.scrollLeft() - 不同浏览器中的不同值

javascript - 向下滚动页面时在侧边栏中显示部分标题(可能使用 BS scrollspy?)

javascript - 如何将JQuery中元素的字符串更改为符号字符?

javascript - 重新绘制谷歌地图以查看隐藏的移动标记

jquery - 单击图像时选择单选按钮

jquery - 使用内联 offsetparent 获取元素左/顶部的实际偏移量

jquery - 如何启用AJAX登录时记住密码?

javascript - 使用 Angular-leaflet-directive 的 Leaflet Curve (Bézier)