监听元素属性改变,绑定事件(应用于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