有四种方法: 

方法1: 在<script>标签内直接写代码

<body>
    <button id="btn">click</button>
    <script>
        document.getElementById("btn").onclick = function(){
            alert("click");
        }
    </script>
</body>

 

方法2: 在使用<script>标签的src属性引入外部js文件

// test.js
// document.getElementById("btn").onclick = function(){ alert("hello") };

// test.html
<body>
    <button id="btn">click</button>
    <script src="./test.js">
        因为src引入了外部文件, 因此写在标签中的代码不会执行.
    </script>
</body>

 

方法3: 通过事件属性

<body>
    <input type="text" onblur="alert(this.value)" />
</body>

 

方法4: 使用URL协议

<body>
    <a href="javascript:alert('hello')">click</a>
</body>

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-22
  • 2021-07-16
  • 2021-08-05
  • 2021-09-18
  • 2021-12-05
猜你喜欢
  • 2022-12-23
  • 2021-09-27
  • 2021-09-22
  • 2022-12-23
  • 2022-12-23
  • 2022-03-03
相关资源
相似解决方案