jQuery click事件未绑定到元素

时间:2018-09-18 03:07:49

标签: javascript jquery google-chrome-extension modal-dialog

我正在为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代码直接粘贴到控制台中,{{ 1}} .popup-close仍然不执行任何操作。

更新:我还尝试了span .popup-close的事件委托,但这不起作用。

更新:我也尝试使用香草javascript绑定到span .popup-close,但这不起作用。 instagram帖子模式启动后,似乎没有任何东西可以绑定到该元素。

1 个答案:

答案 0 :(得分:0)

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

文档here

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”匹配。

相关问题