Chrome扩展程序。使用弹出菜单中的功能分配按钮

时间:2015-03-09 19:18:27

标签: javascript google-chrome-extension

请帮忙!如何在弹出菜单中为按钮分配功能?

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
}

谢谢!

2 个答案:

答案 0 :(得分:1)

popup.html

<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>

popup.js

document.getElementById('button1').onclick = Button1;
document.getElementById('button2').onclick = Button2;

function Button1() {
  // Something
}

function Button2() {
  // Something
}

答案 1 :(得分:0)

  1. 您需要能够识别您的元素。因此,请为其提供唯一ID:

    <a href='#' id="btn1">Message 1</a>
    <br>
    <a href='#' id="btn2">Message 2</a>
    
  2. 您需要将函数绑定到click事件:

    function Button1() {
      // Something
    }
    
    document.getElementById("btn1").addEventListener("click", Button1);
    
  3. 以上内容尚不可行,因为它将在构建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);
    });