几天来,我遇到了一个关于不执行函数的.js脚本中的按钮的问题。
这里我的代码在popup.html里面
<html>
<head>
<script src="popup.js"></script>
</head>
<body>
<div id="panier_container"> </div>
</body>
</html>这里我的代码在popup.js里面
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
//Message en provenance du background
if (msg.text === 'panier') {
var panier_container = document.getElementById("panier_container");
panier_container.innerHTML ="<button id=\"totoButton\"> Affiche TOTO </button>";
}
});
//Fonction toto
function toto() {
alert("toto");
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("totoButton").addEventListener("click", toto);
});当我执行代码时,我会看到弹出窗口中的按钮,但是当我单击该按钮时,什么也不会发生。关于信息,msg来自于我的background.js。
但是,如果我在popup.js中编写这段代码,就可以了:
var panier_container = document.getElementById("panier_container");
panier_container.innerHTML ="<button id=\"totoButton\"> Affiche TOTO </button>";
//Fonction toto
function toto() {
alert("toto");
}
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("totoButton").addEventListener("click", toto);
});使用这段代码,我看到了按钮,当我单击它时,我看到了toto (函数被执行)。
您知道为什么循环chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {中的按钮不执行toto函数吗?
发布于 2017-04-24 16:06:49
请为popup.js尝试以下操作:
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
//Fonction toto
function toto() {
alert("toto");
}
//Message en provenance du background
if (msg.text === 'panier') {
var panier_container = document.getElementById("panier_container");
panier_container.innerHTML ="<button id=\"totoButton\"> Affiche TOTO </button>"; //create the button
document.getElementById("totoButton").addEventListener("click", toto); //attach listener to button just created.
}
});在实际元素存在之前,代码document.getElementById("totoButton").addEventListener("click", toto);被称为,因为元素是在收到消息后创建的。
https://stackoverflow.com/questions/43592472
复制相似问题