jQuery 事件触发

142 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="jquery-3.4.1.js"></script>
  <script>
    $(function () {
      // $(document).on('click mouseenter', function () {
      //   console.log('页面被点击了');
      // })

      // 事件触发1: 简单事件触发, 触发浏览器行为
      // $(document).click();
      // $(document).mouseenter();

      // 事件触发2: 触发浏览器行为
      // $(document).trigger('click');
      // $(document).trigger('mouseenter');

      // 事件触发3: 不触发浏览器行为
      // 比如: 文本框获得焦点的默认行为
      // $(document).triggerHandler('click');
      // $(document).triggerHandler('mouseenter');

      // 例子:
      // 绑定事件
      $('input').on('focus', function () {
        console.log('我获取了焦点');
      });
      // 触发浏览器行为,执行程序,触动事件
      // $(document).click(function () {
      //   $('input').trigger('focus');
      // })
      // 不触发浏览器行为,只执行程序,不触动事件
      $(document).click(function () {
        $('input').triggerHandler('focus');
      })
    })
  </script>
</head>
<body>
  <input type="text">
</body>
</html>
  • 触发浏览器行为:

  • 不触发浏览器行为: