zoukankan      html  css  js  c++  java
  • jQuery下实现检测指定元素加载完毕

    检测元素出现方法。
    虽然是基于 jQuery 的,但是代码很简洁,可以修改成纯js版的。

    jQuery.fn.wait = function (func, times, interval) {
        var _times = times || -1, //100次
        _interval = interval || 20, //20毫秒每次 
        _self = this,
        _selector = this.selector, //选择器
        _iIntervalID; //定时器id
        if( this.length ){ //如果已经获取到了,就直接执行函数
            func && func.call(this);
        } else {
            _iIntervalID = setInterval(function() {
                if(!_times) { //是0就退出
                    clearInterval(_iIntervalID);
                }
                _times <= 0 || _times--; //如果是正数就 --
                
                _self = $(_selector); //再次选择
                if( _self.length ) { //判断是否取到
                    func && func.call(_self);
                    clearInterval(_iIntervalID);
                }
            }, _interval);
        }
        return this;
    }

    使用方法当然也很简单,只有3个参数。
    func 是回调函数,就是当指定元素出现后就执行的函数。
    times 是检测次数,默认是-1,一直检测直到出现为止。
    interval 是检测间隔,默认 20 毫秒一次。

    我们修改下之前的代码

    $("#btn_comment_submit").wait(function() { //等待#btn_comment_submit元素的加载
        this.removeClass("comment_btn").addClass("btn"); //提交按钮
        //这里的 this 就是 $("#btn_comment_submit")
    });
    
    $("#widget_my_zzk").wait(function() { //等待#widget_my_zzk元素的加载
        $(".div_my_zzk").addClass("input-append"); //搜索框
        $(".btn_my_zzk").removeClass("btn_my_zzk").addClass("btn"); //搜索按钮
    });

    是不是很简单、、

    当然,依然不破坏jQuery的链式结构,你依然可以 $("#id").wait(function(){}).hide();

  • 相关阅读:
    LeetCode Find Duplicate File in System
    LeetCode 681. Next Closest Time
    LeetCode 678. Valid Parenthesis String
    LeetCode 616. Add Bold Tag in String
    LeetCode 639. Decode Ways II
    LeetCode 536. Construct Binary Tree from String
    LeetCode 539. Minimum Time Difference
    LeetCode 635. Design Log Storage System
    LeetCode Split Concatenated Strings
    LeetCode 696. Count Binary Substrings
  • 原文地址:https://www.cnblogs.com/axl234/p/3808091.html
Copyright © 2011-2022 走看看