请帮忙!如何在弹出菜单中为按钮分配功能?
popup.html
<html>
<head>
<title>Common Messages for Intercom</title>
<script src="popup.js"></script>
</head>
<body>
<a href='#'>Message 1</a>
<br>
<a href='#'>Message 2</a>
</body>
</html>
popup.js
function Button1() {
// Something
}
function Button2() {
// Something
}
谢谢!
答案 0 :(得分:1)
<html>
<head>
<title>Common Messages for Intercom</title>
</head>
<body>
<a id="button1" href='#'>Message 1</a>
<br>
<a id="button2" href='#'>Message 2</a>
<script src="popup.js"></script>
</body>
</html>
document.getElementById('button1').onclick = Button1;
document.getElementById('button2').onclick = Button2;
function Button1() {
// Something
}
function Button2() {
// Something
}
答案 1 :(得分:0)
您需要能够识别您的元素。因此,请为其提供唯一ID:
<a href='#' id="btn1">Message 1</a>
<br>
<a href='#' id="btn2">Message 2</a>
您需要将函数绑定到click
事件:
function Button1() {
// Something
}
document.getElementById("btn1").addEventListener("click", Button1);
以上内容尚不可行,因为它将在构建DOM之前执行(因此#btn1
尚不存在)。在DOMContentLoaded
侦听器中包装内容以确保DOM已准备就绪:
function Button1() {
// Something
}
function Button2() {
// Something
}
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("btn1").addEventListener("click", Button1);
document.getElementById("btn2").addEventListener("click", Button2);
});