Maison > interface Web > js tutoriel > le corps du texte

JQuery simple et facile à comprendre : événements et jQuery

王林
Libérer: 2023-09-02 10:29:05
original
970 Les gens l'ont consulté

JQuery simple et facile à comprendre : événements et jQuery

Non limité à un seul événement ready()

Il est important de se rappeler que vous pouvez déclarer autant d'événements personnalisés ready() 事件。您不限于将单个 .ready() 事件附加到文档。 ready() que vous devez exécuter dans l'ordre dans lequel ils sont contenus.

Remarque : Passez une fonction jQuery, un raccourci vers une fonction - par ex. jQuery(funciton(){//此处代码}) - 是 jQuery(document).ready()


Ajouter/supprimer des événements à l'aide de bind() et unbind()

Utilisation de

- Vous pouvez ajouter l'un des gestionnaires standard suivants à l'élément DOM approprié. bind() 方法 - 例如jQuery('a').bind('click',function(){})

<ul> <li> blur <li> 焦点 <li> 加载 <li>taille调整 <li> scroll <li> 卸载 <li> 卸载前 <li> click <li> dblclick <li> mousedown <li> mouseup <li> mousemove <li> 鼠标悬停在 <li> mouseout <li> 更改 <li> select <li> 提交 <li> keydown <li> keypress <li> keyup <li> 错误 Apparemment, selon le standard DOM, seuls certains gestionnaires sont cohérents avec des éléments spécifiques.

En plus de cette liste de gestionnaires standards, vous pouvez profiter de

- ainsi que de tous les gestionnaires personnalisés que vous pourriez créer. bind() 附加 jQuery 自定义处理程序 - 例如mouseentermouseleave

Pour supprimer un gestionnaire standard ou un gestionnaire personnalisé, nous transmettons simplement le nom du gestionnaire ou le nom du gestionnaire personnalisé qui doit être supprimé à

et cela supprimera tous les gestionnaires attachés à l'élément. unbind() 方法 - 例如jQuery('a').unbind('click').如果没有参数传递给 unbind()

Les concepts qui viennent d'être abordés sont exprimés dans l'exemple de code ci-dessous.

<!DOCTYPE html>
<html lang="en">
<body>
    <input type="text" value="click me">
    <br>
    <br>
    <button>remove events</button>
    <div id="log" name="log"></div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      // Bind events
      $('input').bind('click', function () { alert('You clicked me!'); });
      $('input').bind('focus', function () {
          // alert and focus events are a recipe for an endless list of dialogs
          // we will log instead
          $('//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15blog').html('You focused this input!');
      });
      // Unbind events
      $('button').click(function () {
          // Using shortcut binding via click()
          $('input').unbind('click');
          $('input').unbind('focus');
          // Or, unbind all events     // $('button').unbind();
      });
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

Remarque : jQuery fournit .bind() 方法的多个快捷方式,用于所有标准 DOM 事件,其中不包括 mouseentermouseleave 等自定义 jQuery 事件。使用这些快捷方式只需将事件名称替换为方法名称 - 例如.click(), mouseout(), 焦点()

Vous pouvez utiliser jQuery pour attacher un nombre illimité de gestionnaires à un seul élément DOM.

jQuery fournit

wrappers. one() 事件处理方法,可以方便地将事件绑定到 DOM 元素上,该事件将被执行一次,然后被删除。 one() 方法只是 bind()unbind()


Appelez par programmation des gestionnaires spécifiques via des méthodes d'événements courtes

Syntaxe du raccourci - par exemple, l'événement

le démontre. .click()mouseout()focus() - 用于将事件处理程序绑定到 DOM 元素,也可用于以编程方式调用处理程序。为此,只需使用快捷事件方法而不向其传递函数即可。理论上,这意味着我们可以将处理程序绑定到 DOM 元素,然后立即调用该处理程序。下面,我通过 click()

<!DOCTYPE html>
<html lang="en">
<body>
    <a>Say Hi</a>
    <!-- clicking this element will alert "hi" -->
    <a>Say Hi</a>
    <!-- clicking this element will alert "hi" -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      // Bind a click handler to all <a> and immediately invoke their handlers
      $('a').click(function () { alert('hi') }).click();
      // Page will alert twice. On page load, a click
      // is triggered for each <a> in the wrapper set.
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

Remarque : Il est également possible d'utiliser des événements Cela fonctionne également pour les espaces de noms et les événements personnalisés. trigger() 方法来调用特定的处理程序 - 例如jQuery('a').click(function(){alert('hi') }).trigger('click')


Objet événement standardisé jQuery

jQuery spécifie les objets événementiels selon les normes du W3C. Cela signifie que vous n'avez pas à vous soucier de l'implémentation spécifique au navigateur de l'objet événement (comme celui d'Internet Explorer

) lorsqu'il est transmis à un gestionnaire de fonction. Vous pouvez utiliser les propriétés et méthodes suivantes des objets événement sans vous soucier des différences entre les navigateurs, car jQuery standardise les objets événement. window.event

事件对象属性

<ul> <li>event.type <li>event.target <li>event.data <li>event.latedTarget <li>event.currentTarget <li>event.pageX <li>event.pageY <li>event.result <li>event.timeStamp

事件对象方法

<ul> <li>event.preventDefault() <li>event.isDefaultPrevented() <li>event.stopPropagation() <li>event.isPropagationStopped() <li>event.stopImmediatePropagation() <li>event.isImmediatePropagationStopped()

要访问规范化的 jQuery 事件对象,只需传递匿名函数,传递给 jQuery 事件方法,一个名为“event”的参数(或任何您想调用的参数)。然后,在匿名回调函数内部,使用参数来访问事件对象。下面是这个概念的一个编码示例。

<!DOCTYPE html>
<html lang="en">
<body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      $(window).load(function (event) { alert(event.type); }); // Alerts "load"
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

Grokking 事件命名空间

通常,我们会在 DOM 中拥有一个对象,该对象需要将多个函数绑定到单个事件处理程序。例如,我们以调整大小处理程序为例。使用 jQuery,我们可以向 window.resize 处理程序添加任意数量的函数。但是,当我们只需要删除其中一个函数而不是全部时,会发生什么情况呢?如果我们使用 $(window).unbind('resize'),则附加到 window.resize 处理程序的所有函数都将被删除。通过命名处理程序(例如 resize.unique),我们可以为特定函数分配一个唯一的钩子以进行删除。

<!DOCTYPE html>
<html lang="en">
<body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      $(window).bind('resize', function ()
      { alert('I have no namespace'); });

      $(window).bind('resize.unique', function () { alert('I have a unique namespace'); });

      // Removes only the resize.unique function from event handler
      $(window).unbind('resize.unique')
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

在上面的代码中,我们向调整大小处理程序添加了两个函数。添加的第二个(文档顺序)调整大小事件使用事件命名空间,然后立即使用 unbind() 删除该事件。我这样做是为了表明附加的第一个函数没有被删除。命名空间事件使我们能够标记和删除分配给单个 DOM 元素上同一处理程序的唯一函数。

除了解除与单个 DOM 元素和处理程序关联的特定函数的绑定之外,我们还可以使用事件命名空间来专门调用(使用 trigger())附加到 DOM 元素的特定处理程序和函数。在下面的代码中,将两个点击事件添加到 <a>, 中,然后使用命名空间,仅调用一个。

<!DOCTYPE html>
<html lang="en">
<body>
    <a>click</a>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      $('a').bind('click',
       function () { alert('You clicked me') });
      $('a').bind('click.unique',
          function () { alert('You Trigger click.unique') });  // Invoke the function passed to click.unique
      $('a').trigger('click.unique');
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

注意:使用的命名空间的深度或数量没有限制 - 例如resize.layout.headerFooterContent

命名空间是保护、调用、删除插件可能需要的任何独占处理程序的好方法。

命名空间适用于自定义事件和标准事件 - 例如click.uniquemyclick.unique


Grokking 活动代表团

事件委托依赖于事件传播(也称为冒泡)。当您单击 <li>(位于 <ul> 内部)中的 <a> 时,单击事件会将 DOM 从 <a> 向上冒泡到 <li><ul> 等等,直到每个具有分配给事件处理程序的函数的祖先元素被触发。

这意味着如果我们将单击事件附加到 <ul>,然后单击封装在 <ul> 内部的 <a>,最终将单击处理程序附加到 <ul>,因为冒泡,会被调用。当它被调用时,我们可以使用事件对象(event.target)来识别DOM中的哪个元素实际上导致事件冒泡开始。同样,这将为我们提供对开始冒泡的元素的引用。

通过这样做,我们似乎可以仅使用单个事件处理程序/声明向大量 DOM 元素添加事件处理程序。这非常有用;例如,一个有 500 行的表,其中每行都需要一个单击事件,可以利用事件委托。检查下面的代码以进行澄清。

<!DOCTYPE html>
<html lang="en">
<body>
    <ul>
        <li><a href="//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15b">remove</a></li>
        <li><a href="//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15b">remove</a></li>
        <li><a href="//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15b">remove</a></li>
        <li><a href="//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15b">remove</a></li>
        <li><a href="//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15b">remove</a></li>
        <li><a href="//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15b">remove</a></li>
    </ul>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      $('ul').click(function (event) { // Attach click handler to <ul> and pass event object
          // event.target is the <a>
          $(event.target).parent().remove(); // Remove <li> using parent()
          return false; // Cancel default browser behavior, stop propagation
      });
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

现在,如果您要逐字单击列表中的实际项目符号之一而不是链接本身,您猜怎么着?您最终将删除 <ul>。为什么?因为所有点击都会冒泡。因此,当您单击项目符号时,event.target<li>,而不是 <a>。既然是这种情况, parent() 方法将获取 <ul> 并将其删除。我们可以更新代码,以便仅在从 <a> 单击 <li> 时,通过向 parent() 方法传递一个元素表达式来删除 <li>

$(event.target).parent('li').remove();
Copier après la connexion

这里重要的一点是,当可点击区域包含多个封装元素时,您必须仔细管理所单击的内容,因为您永远不知道用户可能单击的确切位置。因此,您必须检查以确保点击发生在您期望的元素上。


使用 live() 将事件处理程序应用于 DOM 元素,无论 DOM 更新如何

使用方便的 live() 事件方法,您可以将处理程序绑定到网页中当前和尚未添加的 DOM 元素。 live() 方法使用事件委托来确保新添加/创建的 DOM 元素始终响应事件处理程序,无论 DOM 操作或 DOM 的动态更改如何。使用 live() 本质上是手动设置事件委托的快捷方式。例如,使用 live() 我们可以创建一个按钮,该按钮无限期地创建另一个按钮。

<!DOCTYPE html>
<html lang="en">
<body>
    <button>Add another button</button>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      $('button').live('click', function ()
      { $(this).after("<button>Add another button</button>"); });
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

检查代码后,很明显我们正在使用 live() 将事件委托应用于父元素(代码示例中的 <body> 元素),以便将任何按钮元素添加到DOM 始终响应点击处理程序。

要删除实时事件,我们只需使用 die() 方法 - 例如$('按钮').die().

要带走的概念是 live() 方法可用于将事件附加到使用 AJAX 删除和添加的 DOM 元素。这样,您就不必在初始页面加载后将事件重新绑定到引入 DOM 的新元素。

注释: live() 支持以下处理程序: click, dblclick, mousedown, mouseup, mousemove, phpcncphp cn>mouseover, mouseout , keydown, keypress, keyup

live() 仅适用于选择器。

live() 默认情况下将通过在发送到 live() 方法的函数内使用 return false 来停止传播。


向多个事件处理程序添加函数

可以将事件 bind() 方法传递给多个事件处理程序。这使得将编写一次的相同函数附加到多个处理程序成为可能。在下面的代码示例中,我们将一个匿名回调函数附加到文档上的单击、按键和调整大小事件处理程序。

<!DOCTYPE html>
<html lang="en">
<body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      // Responds to multiple events
      $(document).bind('click keypress resize', function (event) { alert('A click, keypress, or resize event occurred on the document.'); });
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

使用 PreventDefault() 取消默认浏览器行为

当单击链接或提交表单时,浏览器将调用与这些事件关联的默认功能。例如,单击 <a> 链接,Web 浏览器将尝试在当前浏览器窗口中加载 <a> href 属性的值。要阻止浏览器执行此类功能,您可以使用 jQuery 规范化事件对象的 preventDefault() 方法。

<!DOCTYPE html>
<html lang="en">
<body>
    <a href="//m.sbmmt.com/link/51ef70624ca791283ec434a52da0d4e2">jQuery</a>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      // Stops browser from navigating
      $('a').click(function (event) { event.preventDefault(); });
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

使用 stopPropagation() 取消事件传播

事件在 DOM 中传播(也称为冒泡)。当为任何给定元素触发事件处理程序时,也会为所有祖先元素调用所调用的事件处理程序。这种默认行为有助于事件委托等解决方案。要禁止这种默认冒泡,可以使用 jQuery 规范化事件方法 stopPropagation()

<!DOCTYPE html>
<html lang="en">
<body>
    <div><span>stop</span></div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
      $('div').click(function (event) {
          // Attach click handler to <div>
          alert('You clicked the outer div');
      });

      $('span').click(function (event) {
          // Attach click handler to <span>
          alert('You clicked a span inside of a div element');
          // Stop click on <span> from propagating to <div>
          // If you comment out the line below,
          //the click event attached to the div will also be invoked
          event.stopPropagation();
      });
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

在上面的代码示例中,附加到 <div> 元素的事件处理程序将不会被触发。


通过 return false

返回 false - 例如return false - 相当于同时使用 preventDefault()stopPropagation()

<!DOCTYPE html>
<html lang="en">
<body><span><a href="javascript:alert('You clicked me!')" class="link">click me</a></span>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function($){     $('span').click(function(){
      // Add click event to <span>
      window.location='//m.sbmmt.com/link/51ef70624ca791283ec434a52da0d4e2';     });
      $('a').click(function(){
          // Ignore clicks on <a>
          return false;
      });
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

如果您在上面的代码中注释掉 return false 语句,则 alert() 将被调用,因为默认情况下浏览器将执行 href 的值。此外,由于事件冒泡,页面将导航到 jQuery.com。


创建自定义事件并通过trigger()触发它们

通过 jQuery,您可以使用 bind() 方法创建自己的自定义事件。这是通过为 bind() 方法提供自定义事件的唯一名称来完成的。

现在,因为这些事件是自定义的并且浏览器不知道,所以调用自定义事件的唯一方法是使用 jQuery trigger() 方法以编程方式触发它们。检查下面的代码,了解使用 trigger() 调用的自定义事件的示例。

<!DOCTYPE html>
<html lang="en">
<body>
    <div>jQuery</div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
$('div').bind('myCustomEvent', function () {
      // Bind a custom event to <div>
      window.location = '//m.sbmmt.com/link/51ef70624ca791283ec434a52da0d4e2';
  });
      $('div').click(function () {
          // Click the <div> to invoke the custom event
          $(this).trigger('myCustomEvent');
      })
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

克隆事件以及 DOM 元素

默认情况下,使用 clone() 方法克隆 DOM 结构不会另外克隆附加到被克隆的 DOM 元素的事件。为了克隆元素和附加到元素的事件,您必须向 clone() 方法传递一个布尔值 true

<!DOCTYPE html>
<html lang="en">
<body>
    <button>Add another button</button>
    <a href="//m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15b" class="clone">Add another link</a>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
$('button').click(function () {
var $this = $(this);
      $this.clone(true).insertAfter(this);
      // Clone element and its events
      $this.text('button').unbind('click'); // Change text, remove event
  });
      $('.clone').click(function () {
          var $this = $(this);
          $this.clone().insertAfter(this); // Clone element, but not its events
          $this.text('link').unbind('click'); // Change text, remove event
      });
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

获取鼠标在视口中的 X 和 Y 坐标

通过将 mousemove 事件附加到整个页面(文档),您可以检索鼠标指针在画布上的视口内部移动时的 X 和 Y 坐标。这是通过检索 jQuery 规范化事件对象的 pageYpageX 属性来完成的。

<!DOCTYPE html>
<html lang="en">
<body>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function ($) {
$(document).mousemove(function (e) {
      // e.pageX - gives you the X position
      // e.pageY - gives you the Y position
      $('body').html('e.pageX = ' + e.pageX + ', e.pageY = ' + e.pageY);
  });
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

获取鼠标相对于另一个元素的 X 和 Y 坐标

通常需要获取鼠标指针相对于视口或整个文档以外的元素的 X 和 Y 坐标。这通常通过工具提示来完成,其中工具提示是相对于鼠标悬停位置显示的。这可以通过从视口的 X 和 Y 鼠标坐标中减去相对元素的偏移量来轻松完成。

<!DOCTYPE html>
<html lang="en">
<body>
    <!-- Move mouse over div to get position relative to the div -->
    <div style="margin: 200px; height: 100px; width: 100px; background: //m.sbmmt.com/link/93ac0c50dd620dc7b88e5fe05c70e15bccc; padding: 20px">
        relative to this </div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script>  (function($){  $('div').mousemove(function(e){
      //relative to this div element instead of document
      var relativeX = e.pageX - this.offsetLeft;
      var relativeY = e.pageY - this.offsetTop;
      $(this).html('releativeX = ' + relativeX + ', releativeY = ' + relativeY);
  });
  })(jQuery); </script>
</body>
</html>
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:php.cn
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!