繁体   English   中英

事件未触发内容脚本Chrome扩展程序

[英]Event not triggering on a content scripts Chrome extension

我正在构建content scripts Chrome扩展程序。 我已经动态地向网页添加了一个按钮,但是此按钮上的事件监听器不会触发。

这是manifest.json

{
  "manifest_version": 2,
  "name": "my extension",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab"
  ],
  "content_scripts": [
      {
        "matches": ["http://127.0.0.1:8000/*"],
        "js": ["jquery.js", "script.js"],
        "run_at": "document_end"
      }
  ]
}

这是script.js

document.body.style.backgroundColor = "yellow";
var button = $('<input id="btn" type="button"/>');
$("body").append(button);  

$("#btn").on("click", function(){
    document.body.style.backgroundColor = "red"; 
});

该按钮被添加到页面,背景变为黄色,但单击按钮时不会变为红色。

如果疑似问题与按钮ID有关 - 请注意您根本不需要 ID。

document.body.style.backgroundColor = "yellow";
var button = $('<input id="btn" type="button"/>');
$("body").append(button);  

button.on("click", function(){ // Notice you don't need to search for it again!
    document.body.style.backgroundColor = "red"; 
});

但是,在这种情况下,您需要保持button变量才能再次找到它。

这个唯一的ID可以帮助你;)

document.body.style.backgroundColor = "yellow";
uniqueId = 'btn' + Date.now();
var button = $('<input id="' + uniqueId + '" type="button"/>');
$("body").append(button);

$("#" + uniqueId).on("click", function(){
  document.body.style.backgroundColor = "red";
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM