萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 等待元素加載完成插件:.wait() 實現與應用

無法修改頁面源碼(如博客園、第三方嵌入頁)時,需監聽異步渲染的元素出現再操作。封裝 $.fn.wait 輪詢選擇器,元素出現即執行回調。

插件代碼

$.fn.wait = function(fn, times = -1, interval = 20){
    const $self = this;
    const selector = this.selector;
    let timer;

    if(this.length){ // 已存在
        fn.call(this);
        return this;
    }

    timer = setInterval(() => {
        if(times === 0){ clearInterval(timer); return; }
        if(times > 0) times--;

        const $el = $(selector);
        if($el.length){
            fn.call($el);
            clearInterval(timer);
        }
    }, interval);

    return this; // 保持鏈式
};

使用示例

// 等待 AJAX 渲染的提交按鈕
$('#btn_comment_submit').wait(function(){
    this.removeClass('comment_btn').addClass('btn');
});

// 等待搜索框容器
$('#widget_my_zzk').wait(function(){
    $('.div_my_zzk').addClass('input-append');
    $('.btn_my_zzk').removeClass('btn_my_zzk').addClass('btn');
}, 100, 50); // 最多檢測 100 次,每 50ms 一次

設計細節

  • 參數預設:times=-1 無限輪詢,interval=20ms 平衡響應與性能。
  • 自動清理:找到元素或次數耗盡自動 clearInterval。
  • 上下文綁定:回調內 this 指向匹配到的 jQuery 對象。
  • 鏈式保留:返回 this 允許 .wait(fn).hide(),雖然元素未存在時後續鏈式無意義。

現代替代:MutationObserver

new MutationObserver((mutations, obs) => {
    const el = document.querySelector('#btn_comment_submit');
    if(el){
        $(el).removeClass('comment_btn').addClass('btn');
        obs.disconnect();
    }
}).observe(document.body, {childList: true, subtree: true});

原生 MutationObserver 事件驅動、零輪詢、性能極佳,推薦現代項目使用。

copyright © 萬盛學電腦網 all rights reserved