方法一:利用mutationObserver監聽, 原文鏈接:(10條消息) js實現監聽dom元素的屬性變化_D_bel的博客-CSDN博客_js監聽dom變化
var flag = true var targetNode = jQuery('.detention-mask')[0];//content監聽的元素 //options:監聽的屬性 var options = { attributes: true, childList: true, subtree: true, attributeOldValue: true, attributeFilter: ['style'] }; //回調事件 function callback(mutationsList, observer) { if (flag) { alert(1111) jQuery('.detention-mask .detention-recommend .detention-recommend_item').on('click', function () { console.log($(this)) }) flag = false } } var mutationObserver = new MutationObserver(callback); mutationObserver.observe(targetNode, options);
方法二:利用setInterval持續判斷,當屬性等於需要的屬性值時觸發代碼並清除計時器
var timer = setInterval(function () { if (jQuery('.detention-mask').css('display') == 'block') { alert(111) jQuery('.detention-mask .detention-recommend .detention-recommend_item').on('click', function () { console.log($(this)) }) clearInterval(timer) } }, 100);