jQuery-处理事件

时间:2020-02-23 14:46:09  来源:igfitidea点击:

在本教程中,我们将学习有关使用jQuery处理事件的知识。

document ready

当DOM完成时,会触发一个事件,以表明它已准备就绪。
我们可以使用jQuery监听此ready事件,并且仅在此事件之后运行我们的jQuery代码。

为此,我们编写以下代码。

$(document).ready(function(){
  console.log("I am ready...");
});

上面的代码仅在触发DOM ready事件后才显示"我准备好..."。

点击click

为了处理click事件,我们使用click方法。

在下面的示例中,当单击具有ID" sample-button1"的按钮时,将显示一个警告框。

$("#sample-button1").click(function(){
  alert("I am clicked");
});

我们可以使用click()方法来处理click事件,但是新的jQuery API建议我们使用on()方法。

on click

为了使用on()方法处理click事件,我们必须传递click属性值和一个处理click事件的函数。

在下面的示例中,当单击具有ID" sample-button1"的按钮时,将在浏览器控制台中显示一条消息。

$("#sample-button1").on("click", function(){
  console.log("Button Clicked...");
});

在悬停时

为了处理悬停事件,我们必须传递hover和一个函数来处理悬停事件到on()方法。

在以下示例中,当鼠标悬停在ID为" sample-div1"的div上方时,将在浏览器控制台中显示一条消息。

$("#sample-div1").on("hover", function(e){
  if (e.type == "mouseenter") {
    console.log("Mouse entered...");
  } else if (e.type == "mouseleave") {
    console.log("Mouse left...");
  }
});

在提交时

另一个常用事件是提交表单时触发的submit事件。
为了捕获此事件,我们将submit传递给on()方法。

在下面的示例中,我们有一个ID为" sample-form1"的表单,并且正在处理Submit事件。

$("#sample-form1").on("submit", function(){

  console.log("Form submitted...");

  //this will prevent reloading of page
  return false;

});

提交ID为" sample-form1"的表单时,上面的代码将打印"表单已提交..."。

结合多个事件

我们可以合并多个事件并将其传递给on()方法。

在以下示例中,我们将合并click事件,mouseenter事件和mouseleave事件,并将它们传递给on()方法。

$("#sample-div1").on("click mouseenter mouseleave", function(e) {
  //handle mouseenter event
  if (e.type == "mouseenter") {
    console.log("Mouseenter event fired...");
  }

  //handle mouseleave event
  else if (e.type == "mouseleave") {
    console.log("Mouseleave event fired...");
  }

  //handle click event
  else if (e.type == "click") {
    console.log("Click event fired...");
  }
});

事件链

我们也可以使用on()方法链接事件。

在以下示例中,我们链接了click和mouseenter事件。

$("#sample-div1")
  .on("click", function(){
    console.log("Click event fired...");
  })
  .on("mouseenter", function(){
    console.log("Mouseenter event fired...");
  });

从事件处理程序访问元素

我们使用this关键字从事件处理函数内部访问元素。

在以下示例中,我们有一个ID为" sample-div1"的div。
现在假设我们要在单击该div时向其添加" clicked"类。
为此,我们将编写以下代码。

$("#sample-div1").on("click", function(){
  
  //get the element using this keyword and add clicked class
  $(this).addClass("clicked");

});

在上面的代码中,$(this)是指ID为" sample-div1"的div。

事件触发

我们可以使用trigger()方法触发一个事件。

在下面的示例中,当单击具有ID" sample-button1"的按钮时,我们将触发ID为" sample-form1"的表单的Submit事件。

$("#sample-button1").on("click", function(){
  $("#sample-form1").trigger("submit");
});

移除事件

我们可以使用off()方法从元素中删除或者解除绑定事件。

如果要删除绑定到给定元素的所有事件,则只需调用bind()方法。

在以下示例中,我们将取消绑定ID为" sample-div1"的div中的所有事件。

$("#sample-div1").off();

我们还可以通过将特定事件传递给off()方法来解除绑定。

在以下示例中,我们从ID为" sample-div1"的div中解除绑定" click"事件。

$("#sample-div1").off("click");