javascript - 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
span
with vanilla javascript,但这不起作用。当 Instagram 帖子模式启动时,似乎没有任何东西可以绑定到这个元素。
解决方案
您可以使用$('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”。
推荐阅读
- powershell - 如何将 Chocolatey 函数、核心和扩展导入 PowerShell 会话?
- jenkins - 单击 Web 按钮时,Jenkins 中止下游作业
- python - 检查 getargvalues 仅获取当前帧,如何传递不同 Python 文件的模块?
- java - 在哪里可以找到有关如何使用 Tesseract API 的说明文件,或者是否有其他方法可以修复此错误?
- python - 无法使用 datetime 创建具有空天槽的计时器
- javascript - MomentJS 有时会添加错误的小时数
- ruby-on-rails - 使用 simple-form 为关联生成复选框时,如何隐藏出现在图例标记内的表单标题?
- python - 为什么我的函数检查英语应用程序对非英语应用程序返回 True?
- python - 通过在发布请求中发送文件名,我无法从我的应用程序中找到本地文件。我如何找到该文件?
- node.js - node server only loads on safari localhost and not chrome's