Home  >  Article  >  Web Front-end  >  Deep understanding of events in JavaScript

Deep understanding of events in JavaScript

青灯夜游
青灯夜游forward
2020-09-28 17:56:582482browse

Deep understanding of events in JavaScript

In this article, we will discuss event handlers, event listeners, and event objects. We'll also cover three different ways to handle events, as well as some of the most common ones. By understanding events, you will be able to provide users with a more interactive web experience.

Events are operations that occur in the browser and can be initiated by the user or the browser itself. Here are some common events that happen on websites:

  • Page completes loading

  • User clicks a button

  • User hovers over dropdown list

  • User submits form

  • User presses key on keyboard

By encoding JavaScript responses that execute on events, developers can display messages to the user, validate data, react to button clicks, and perform many other actions.

Event Handlers and Event Listeners

When the user clicks a button or presses a key, an event is triggered. These are called click events or key events respectively.

An event handler is a JavaScript function that runs when an event triggers.

An event listener is attached to a responsive interface element, which allows a specific element to wait and "listen" for a given event to fire.

There are three ways to assign events to elements:

  • Inline event handler

  • Event handler properties

  • Event Listener

We'll go over these three methods in detail to make sure you're familiar with each method of triggering an event, and then discuss the specifics of each method Pros and cons.

Inline Event Handler Properties

To start learning about event handlers, we first consider inline event handlers. Let's start with a very basic example consisting of a button element and a p element. We want the user to click a button to change the text content of p.

Let’s start with an HTML page with a button. We will reference a JavaScript file to which we will add code later.

<!DOCTYPE html>
<html>
  
  <head>
    <title>Events</title></head>
  
  <body>
    <!-- Add button -->
    <button>Click me</button>
    <p>Try to change me.</p>
  </body>
  <!-- Reference JavaScript file -->
  <script src="js/events.js"></script>

</html>

Directly on the button, we will add an attribute called onclick. The property value will be a function we created called changeText().

<!DOCTYPE html>
<html>
  
  <head>
    <title>Events</title></head>
  
  <body>
    <button onclick="changeText()">Click me</button>
    <p>Try to change me.</p>
  </body>
  <script src="js/events.js"></script>

</html>

Let's create the events.js file, which is located in the js/ directory here. In it, we will create the changeText() function, which will modify the textContent of the p element.

// Function to modify the text content of the paragraph
const changeText = () = >{
    const p = document.querySelector(&#39;p&#39;);

    p.textContent = "I changed because of an inline event handler.";
}

The first time you load events.html, you'll see a page that looks like this:

Deep understanding of events in JavaScript

However, when you or another user clicks the button, The text of the p tag will change from Try to change me to . I changed it because of inline event handlers.

Deep understanding of events in JavaScript

Inline event handlers are a straightforward way to start understanding events, but they should generally not be used beyond testing and educational purposes.

You can compare inline event handlers to inline CSS styles on HTML elements. Maintaining a separate class stylesheet is more practical than creating inline styles on each element, just like maintaining JavaScript that is handled entirely through a separate script file rather than adding handlers to each element.

Event Handler Properties

The next step in inlining event handlers is the event handler properties. This is very similar to an inline handler, except we set the attribute of the element in JavaScript rather than in HTML.

The settings here are the same, except we no longer include onclick="changeText()":

… < body >

<button > Click me < /button>

    <p>I will change.</p >

</body>
…/

Our function will also Stay similar, only now we need to access the button element in JavaScript. We can simply access onclick just like we would access style or id or any other element attribute and then assign the function reference.

// Function to modify the text content of the paragraph
const changeText = () = >{
    const p = document.querySelector(&#39;p&#39;);

    p.textContent = "I changed because of an event handler property.";
}

// Add event handler as a property of the button element
const button = document.querySelector(&#39;button&#39;);
button.onclick = changeText;

Note: Event handlers do not follow the camelCase convention that most JavaScript code follows. Note that the code is onclick, not onclick.

When you first load a web page, your browser will display the following:

Deep understanding of events in JavaScript

Now, when you click this button, it will have a Similar effect:

Deep understanding of events in JavaScript

#Note that when passing the function reference to the onclick attribute, we do not include the parentheses because we are not calling the function at that time, but just passing it citation.

事件处理程序属性的可维护性略好于内联处理程序,但它仍然存在一些相同的障碍。例如,尝试设置多个单独的onclick属性将导致覆盖除最后一个外的所有属性,如下所示。

const p = document.querySelector(&#39;p&#39;);
const button = document.querySelector(&#39;button&#39;);

const changeText = () = >{
    p.textContent = "Will I change?";
}

const alertText = () = >{
    alert(&#39;Will I alert?&#39;);
}

// Events can be overwritten
button.onclick = changeText;
button.onclick = alertText;

在上面的例子中,单击按钮只会显示一个警告,而不会更改p文本,因为alert()代码是最后添加到属性的代码。

Deep understanding of events in JavaScript

了解了内联事件处理程序和事件处理程序属性之后,让我们转向事件侦听器。

事件监听器

JavaScript事件处理程序的最新添加是事件侦听器。事件侦听器监视元素上的事件。我们将使用addEventListener()方法侦听事件,而不是直接将事件分配给元素上的属性。

addEventListener()接受两个强制参数——要侦听的事件和侦听器回调函数。

事件监听器的HTML与前面的示例相同。

… < button > Click me < /button>

    <p>I will change.</p > …

我们仍然将使用与以前相同的changeText()函数。我们将把addEventListener()方法附加到按钮上。

// Function to modify the text content of the paragraph
const changeText = () = >{
    const p = document.querySelector(&#39;p&#39;);

    p.textContent = "I changed because of an event listener.";
}

// Listen for click event
const button = document.querySelector(&#39;button&#39;);
button.addEventListener(&#39;click&#39;, changeText);

注意,对于前两个方法,click事件被称为onclick,但是对于事件监听器,它被称为click。每个事件监听器都会从单词中删除这个词。在下一节中,我们将查看更多其他类型事件的示例。

当您用上面的JavaScript代码重新加载页面时,您将收到以下输出:

Deep understanding of events in JavaScript

初看起来,事件监听器看起来与事件处理程序属性非常相似,但它们有一些优点。我们可以在同一个元素上设置多个事件侦听器,如下例所示。

const p = document.querySelector(&#39;p&#39;);
const button = document.querySelector(&#39;button&#39;);

const changeText = () = >{
    p.textContent = "Will I change?";
}

const alertText = () = >{
    alert(&#39;Will I alert?&#39;);
}

// Multiple listeners can be added to the same event and element
button.addEventListener(&#39;click&#39;, changeText);
button.addEventListener(&#39;click&#39;, alertText);

在本例中,这两个事件都将触发,一旦单击退出警告,就向用户提供一个警告和修改后的文本。

通常,将使用匿名函数而不是事件侦听器上的函数引用。匿名函数是没有命名的函数。

// An anonymous function on an event listener
button.addEventListener(&#39;click&#39;, () = >{
    p.textContent = "Will I change?";
});

还可以使用removeEventListener()函数从元素中删除一个或所有事件。

// Remove alert function from button element
button.removeEventListener(&#39;click&#39;, alertText);

此外,您可以在文档和窗口对象上使用addEventListener()。

事件监听器是当前在JavaScript中处理事件的最常见和首选的方法。

常见的事件

我们已经了解了使用click事件的内联事件处理程序、事件处理程序属性和事件侦听器,但是JavaScript中还有更多的事件。下面我们将讨论一些最常见的事件。

鼠标事件

鼠标事件是最常用的事件之一。它们指的是涉及单击鼠标上的按钮或悬停并移动鼠标指针的事件。这些事件还对应于触摸设备上的等效操作。

事件
描述
click 当鼠标被按下并释放到元素上时触发
dblclick 当元素被单击两次时触发
mouseenter 当指针进入元素时触发
mouseleave 当指针离开一个元素时触发
mousemove 每当指针在元素中移动时触发

Click is a compound event, consisting of the combined mousedown and mouseup events, which are triggered when the mouse button is pressed or raised respectively.

Use mouseenter and mouseleave simultaneously to create a hover effect that will last as long as the mouse pointer stays on the element.

Form Events

Form events are form-related actions, such as which input elements are being selected or unselected, and which form is being submitted.

##submitFired when the form is submittedfocusFired when an element (such as an input) receives focus blurWhen an element Triggered when focus is lost
Event
Description
#Focus is achieved when an element is selected, e.g. by mouse click or by navigating to it via the TAB key.

JavaScript is commonly used to submit forms and send values ​​to backend languages. The advantages of using JavaScript to send a form are that submitting the form does not require reloading the page, and the required input fields can be validated using JavaScript.

Keyboard events

Keyboard events are used to handle keyboard operations such as pressing a key, raising a key, and holding a key.

EventDescription##keydownkeyupkeypressAlthough they look similar, the keydown and keypress events do not access all the exact same keys. keydown will acknowledge each key pressed, while keypress will omit keys that do not generate characters, such as SHIFT, ALT, or DELETE.

A key is pressed It will trigger once when
Trigger once when releasing the key
Continuously when pressing the key Fire

Keyboard events have specific properties for accessing individual keys.

If we pass a parameter called an event object to an event listener, we can access more information about the action that occurred. The three properties related to the keyboard object include keyCode, key and code.

For example, if the user presses the letter a key on the keyboard, the following properties related to that key will appear:

PropertieskeyCodekeycode

为了展示如何通过JavaScript控制台收集这些信息,我们可以编写以下代码行。

// Test the keyCode, key, and code properties
document.addEventListener(&#39;keydown&#39;, event = >{
    console.log(&#39;key: &#39; + event.keyCode);
    console.log(&#39;key: &#39; + event.key);
    console.log(&#39;code: &#39; + event.code);
});

一旦在控制台上按下ENTER键,现在就可以按键盘上的键了,在本例中,我们将按a。

输出:

keyCode: 65
key: a
code: KeyA

keyCode属性是一个与已按下的键相关的数字。key属性是字符的名称,它可以更改——例如,用SHIFT键按下a将导致键为a。code属性表示键盘上的物理键。

注意,keyCode正在被废弃,最好在新项目中使用代码。

事件对象

该Event对象由所有事件都可以访问的属性和方法组成。除了通用Event对象之外,每种类型的事件都有自己的扩展名,例如KeyboardEvent和MouseEvent。

该Event对象作为参数传递给侦听器函数。它通常写成event或e。我们可以访问事件的code属性keydown来复制PC游戏的键盘控件。

要试用它,请使用

标记创建基本HTML文件并将其加载到浏览器中。

<!DOCTYPE html>
<html>
  
  <head>
    <title>Events</title></head>
  
  <body>
    <p>
    </p>
  </body>

</html>

然后,在浏览器的开发者控制台中键入以下JavaScript代码。

// Pass an event through to a listener
document.addEventListener(&#39;keydown&#39;, event = >{
    var element = document.querySelector(&#39;p&#39;);

    // Set variables for keydown codes
    var a = &#39;KeyA&#39;;
    var s = &#39;KeyS&#39;;
    var d = &#39;KeyD&#39;;
    var w = &#39;KeyW&#39;;

    // Set a direction for each code
    switch (event.code) {
    case a:
        element.textContent = &#39;Left&#39;;
        break;
    case s:
        element.textContent = &#39;Down&#39;;
        break;
    case d:
        element.textContent = &#39;Right&#39;;
        break;
    case w:
        element.textContent = &#39;Up&#39;;
        break;
    }
});

当您按下一个键- ,a,s,d或者w-你会看到类似以下的输出:

Deep understanding of events in JavaScript

从这里开始,您可以继续开发浏览器的响应方式以及按下这些键的用户,并可以创建更加动态的网站。

接下来,我们将介绍一个最常用的事件属性:target属性。在下面的示例中,我们div在一个内部有三个元素section。

<!DOCTYPE html>
<html>
  
  <head>
    <title>Events</title></head>
  
  <body>
    <section>
      <div id="one">One</div>
      <div id="two">Two</div>
      <div id="three">Three</div></section>
  </body>

</html>

使用事件。在浏览器的开发人员控制台中,我们可以将一个事件侦听器放在外部section元素上,并获得嵌套最深的元素。

const section = document.querySelector(&#39;section&#39;);

// Print the selected target
section.addEventListener(&#39;click&#39;, event = >{
    console.log(event.target);
});

单击其中任何一个元素都将使用event.target将相关特定元素的输出返回到控制台。这非常有用,因为它允许您只放置一个事件侦听器,该侦听器可用于访问许多嵌套元素。

Deep understanding of events in JavaScript

使用Event对象,我们可以设置与所有事件相关的响应,包括通用事件和更具体的扩展。

结论

事件是在网站上发生的操作,例如单击,悬停,提交表单,加载页面或按键盘上的键。当我们能够让网站响应用户所采取的操作时,JavaScript就变得真正具有互动性和动态性。

更多编程相关知识,请访问:编程入门!!

Description Example
The number associated with the key. 65
represents the character name a
Indicates the physical key pressed KeyA

The above is the detailed content of Deep understanding of events in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:digitalocean.com. If there is any infringement, please contact admin@php.cn delete