首页 > 解决方案 > jQuery单击事件未绑定到元素

问题描述

我正在为 Instagram 构建一个 Chrome 扩展程序。我的问题发生在 instagram 的“单个帖子”页面上(当您单击帖子并显示为模式时)。

当显示帖子模式时,我使用以下代码将我自己的自定义模式/弹出窗口附加到页面:

function attachUpgradePopup(str) {
    $(".upgrade-popup-container").remove();
    $("body").append(`
        <div class="upgrade-popup-container">
            <div class="upgrade-popup">
                <img class="popup-img" src="https://i.imgur.com/6sOdwYs.png">
                <p class="upgrade-popup-text">This post is ${str}.</p><br>
                <p class="upgrade-popup-text">To do this you must upgrade to</p>
                <p class="upgrade-popup-text">the PRO version!</p>
                <span class="popup-close">X</span>
            </div>
        </div>
    `);
    $(".popup-close").click(function() {
        console.log('closing')
        $(".upgrade-popup-container").remove();
    });
}

我的问题是该click功能.popup-close span由于某种原因无法正常工作。我知道这与打开的 instagram 帖子模式有关,因为当没有打开帖子模式并且效果很好时,我在其他地方/页面使用此自定义弹出窗口。但是当 Instagram 帖子模式打开.popup-close span时,我点击它时什么也不做。

为什么会这样?

我知道这无关,z-index因为我已经测试过了。我觉得 Instagram 可能会在后台运行某种 jQuery,这会破坏我的click事件绑定,因为即使我打开两个模式然后将click代码直接粘贴到控制台中,它.popup-close span仍然什么也不做。

更新:我也尝试过事件委托,.popup-close span并且不起作用。

更新:我也尝试绑定到.popup-close spanwith vanilla javascript,但这不起作用。当 Instagram 帖子模式启动时,似乎没有任何东西可以绑定到这个元素。

标签: javascriptjquerygoogle-chrome-extensionmodal-dialog

解决方案


您可以使用$('body').on('click', eventHandlerFunction);

文档在这里

function attachUpgradePopup(str) {
    $(".upgrade-popup-container").remove();
    $("body").append(`
        <div class="upgrade-popup-container">
            <div class="upgrade-popup">
                <img class="popup-img" src="https://i.imgur.com/6sOdwYs.png">
                <p class="upgrade-popup-text">This post is ${str}.</p><br>
                <p class="upgrade-popup-text">To do this you must upgrade to</p>
                <p class="upgrade-popup-text">the PRO version!</p>
                <span class="popup-close">X</span>
            </div>
        </div>
        `);
    $("body").on("click", ".popup-close", function () {
        console.log('closing')
        $(".upgrade-popup-container").remove();
    });
}

基本上$("body")会捕获点击并检查目标元素是否匹配“.popup-close”。


推荐阅读