javascript - 在 Chrome 扩展中单击元素之前的事件监听器运行函数

标签 javascript html google-chrome google-chrome-extension event-handling

我最近一直在为 Google Chrome 创建一个扩展, list 版本 2 说我不能在我创建的 html 文件中使用事件处理程序(onclick、onmouseover、ondblclick 等)。它确实说我可以在我链接到它的脚本上创建它们。唯一的问题是,当我单击该图标时,该函数会在我单击实际的 div 元素之前运行。我真的很困惑我做错了什么,所以我尝试了几种方法:

我的 manifest.json 文件似乎工作正常,我没有收到任何错误,每个链接的页面都有效,icon.png 文件也是如此。

{
    "name" : "Test",
    "version" : "1.0",
    "manifest_version" : 2,
    "description" : "Trying it out",
    "browser_action" : {
"default_icon" : "icon.png",
"defalut_title" : "Test",
"default_popup" : "popup.html"
},
    "chrome_url_overrides" : {
"newtab" : "newtab.html"
}
}

这是我放入 popup.html 文件的内容:

<html>
<head></head>
<body>
<div id="submitButton">Submit!</div>
</body>
</html> <!-- The rest of the code is unnecessary since it is not used as for now -->
<script type="text/javascript" src="popup.js"></script>

我的 popup.js 文件有这个功能:

var sButton = document.getElementById('submitButton');
sButton.addEventListener('onclick',alert('This is not supposed to happen until I click the div'),false);

//I also put the alert in a function like so: function() {alert('what it said')}

在我发现这种方式行不通之后,我采用了这种方式:

sButton.onclick = function() {alert('same thing')}

当我单击扩展程序图标时,我执行的任何一种方法都会发出警报,它甚至没有运行 popup.html。我不知道我是否需要向它添加一个功能,但由于我是这个(我的第一个扩展)的新手,我真的不知道我是否应该添加一个特殊的 chrome 方法或其他东西。我查看了 Google Dev 页面,但没有帮助。它只教会了我基础知识。

任何帮助将不胜感激,在此先感谢。

最佳答案

应该是:

sButton.addEventListener('click',
    function() {alert('This is not supposed to happen until I click the div'),false);});

您正在调用 alert() 并将其结果传递给 addEventListener。您需要传递一个将调用 alert() 的函数。

顺便说一句,在 addEventListener 中指定事件时,您不包括 on 前缀——它只是 click

关于javascript - 在 Chrome 扩展中单击元素之前的事件监听器运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18638109/

相关文章:

javascript - 样式表,下划线输入

javascript - Stripe 形式不创建 token

html - 如何将表单中的字段放置为具有相同的高度和宽度

jquery - 关闭模式会使 body 向上移动并破坏 chrome 中的滚动

javascript - 使用 ajax 在 BackBone 中发出 GET 请求

javascript - 正则表达式来测试箭头功能

html - 在容器内垂直居中 div

html - 背景颜色在包装器中不起作用

javascript - 桌面上的innerWidth 和outerWidth 奇怪

html - Chrome 错误中的边界半径?