無法修改頁面源碼(如博客園、第三方嵌入頁)時,需監聽異步渲染的元素出現再操作。封裝 $.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(),雖然元素未存在時後續鏈式無意義。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 事件驅動、零輪詢、性能極佳,推薦現代項目使用。