監聽元素屬性改變,綁定事件(應用於display初始為none)


方法一:利用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);

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM