搜尋
首頁web前端js教程了解 DOM 事件
了解 DOM 事件Sep 30, 2024 pm 06:30 PM

Understanding DOM Events

DOM Events is what makes a webpage interactive. Using DOM events is what makes a page click or a form submit, it lets developers create an engaging user experience.

Some examples of DOM Events is when a user clicks the mouse, when a webpage has loaded, when an image has loaded, when a HTML form is submitted, and when a user presses a key.

In this article we will simplify key concepts in DOM Events and explore how to handle them.

1. addEventListener

addEventListener, attaches an event handler to elements, it allows you to define how the element reacts to the users interaction to the page.

Example: The code below is adding a 'click' event to display the cocktails details when the image is clicked.

`img.addEventListener('click', () => handleClick(cocktail));`

2. querySelector

querySelector, allows you to select an element using CSS-like selectors. It’s one of the most versatile ways to target elements.

Example: This code is creating a collapsible section on the webpage. document.querySelectorAll is selecting all the h3 elements on the webpage and returns a NodeList of all the matching elements.

const setupCollapsibles = () => {
  const collapsibles = document.querySelectorAll('.collapsible h3');

3. getElementById and getElementsByClassName

getElementById targets a single element by its unique id.

Similarly, getElementsByClassName selects all elements with a specific class and returns them as a collection.

Example: Below, getElementById finds an element by its id attribute in the HTML document.

It is being used here to access the specific form inputs, new-name, new-ingredients, new-image, new-recipe and retrieves their values.

These values are then stored in the properties of the newCocktail object which is defined with const.

This way, when the user submits a form to create a new cocktail it is stored in a structured way inside the newCocktail object.

const newCocktail = {
      name: document.getElementById('new-name').value,
      ingredients: document.getElementById('new-ingredients').value.split(', '),
      image: document.getElementById('new-image').value,
      recipe: document.getElementById('new-recipe').value,
    }; 

4. DOMContentLoaded

The DOMContentLoaded event ensures your JavaScript runs only after the DOM is fully loaded, preventing errors from trying to access elements before they're available.

Example: DOMContentLoaded, is an event that fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, or other external resources to fully load.

It ensures that the DOM is fully built and accessible, so you can safely interact with elements in the HTML, such as adding event listeners or manipulating the DOM.

In the code below, the browser is telling you, that the document is now available and the user can start interacting with it.

document.addEventListener('DOMContentLoaded', () => {
  setupEditListener();
  setupDeleteListener();
});

Final Notes

DOM events are fundamental in making a webpage interactive and engaging for users. By understanding and utilizing core methods like addEventListener, querySelector, getElementById, and getElementsByClassName, you can create dynamic user interfaces that respond to clicks, form submissions, and more.

Additionally, the DOMContentLoaded event ensures that your scripts are executed only after the DOM is fully loaded, preventing potential errors and ensuring smooth user interaction.

In summary, DOM events allow you to:

  • Attach event handlers with addEventListener for responsive interactivity.

  • Select elements with querySelector or getElementById to dynamically update content.

  • Manage event-triggered actions based on user input, such as form submissions.

  • Ensure your scripts run at the right time using DOMContentLoaded.

With these techniques, you can transform static web pages into interactive experiences that enhance user engagement.

以上是了解 DOM 事件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在JavaScript中替換字符串字符在JavaScript中替換字符串字符Mar 11, 2025 am 12:07 AM

JavaScript字符串替換方法詳解及常見問題解答 本文將探討兩種在JavaScript中替換字符串字符的方法:在JavaScript代碼內部替換和在網頁HTML內部替換。 在JavaScript代碼內部替換字符串 最直接的方法是使用replace()方法: str = str.replace("find","replace"); 該方法僅替換第一個匹配項。要替換所有匹配項,需使用正則表達式並添加全局標誌g: str = str.replace(/fi

構建您自己的Ajax Web應用程序構建您自己的Ajax Web應用程序Mar 09, 2025 am 12:11 AM

因此,在這裡,您準備好了解所有稱為Ajax的東西。但是,到底是什麼? AJAX一詞是指用於創建動態,交互式Web內容的一系列寬鬆的技術。 Ajax一詞,最初由Jesse J創造

10個JQuery Fun and Games插件10個JQuery Fun and Games插件Mar 08, 2025 am 12:42 AM

10款趣味橫生的jQuery遊戲插件,讓您的網站更具吸引力,提升用戶粘性!雖然Flash仍然是開發休閒網頁遊戲的最佳軟件,但jQuery也能創造出令人驚喜的效果,雖然無法與純動作Flash遊戲媲美,但在某些情況下,您也能在瀏覽器中獲得意想不到的樂趣。 jQuery井字棋遊戲 遊戲編程的“Hello world”,現在有了jQuery版本。 源碼 jQuery瘋狂填詞遊戲 這是一個填空遊戲,由於不知道單詞的上下文,可能會產生一些古怪的結果。 源碼 jQuery掃雷遊戲

如何創建和發布自己的JavaScript庫?如何創建和發布自己的JavaScript庫?Mar 18, 2025 pm 03:12 PM

文章討論了創建,發布和維護JavaScript庫,專注於計劃,開發,測試,文檔和促銷策略。

jQuery視差教程 - 動畫標題背景jQuery視差教程 - 動畫標題背景Mar 08, 2025 am 12:39 AM

本教程演示瞭如何使用jQuery創建迷人的視差背景效果。 我們將構建一個帶有分層圖像的標題橫幅,從而創造出令人驚嘆的視覺深度。 更新的插件可與JQuery 1.6.4及更高版本一起使用。 下載

如何在瀏覽器中優化JavaScript代碼以進行性能?如何在瀏覽器中優化JavaScript代碼以進行性能?Mar 18, 2025 pm 03:14 PM

本文討論了在瀏覽器中優化JavaScript性能的策略,重點是減少執行時間並最大程度地減少對頁面負載速度的影響。

使用jQuery和Ajax自動刷新DIV內容使用jQuery和Ajax自動刷新DIV內容Mar 08, 2025 am 12:58 AM

本文演示瞭如何使用jQuery和ajax自動每5秒自動刷新DIV的內容。 該示例從RSS提要中獲取並顯示了最新的博客文章以及最後的刷新時間戳。 加載圖像是選擇

Matter.js入門:簡介Matter.js入門:簡介Mar 08, 2025 am 12:53 AM

Matter.js是一個用JavaScript編寫的2D剛體物理引擎。此庫可以幫助您輕鬆地在瀏覽器中模擬2D物理。它提供了許多功能,例如創建剛體並為其分配質量、面積或密度等物理屬性的能力。您還可以模擬不同類型的碰撞和力,例如重力摩擦力。 Matter.js支持所有主流瀏覽器。此外,它也適用於移動設備,因為它可以檢測觸摸並具有響應能力。所有這些功能都使其值得您投入時間學習如何使用該引擎,因為這樣您就可以輕鬆創建基於物理的2D遊戲或模擬。在本教程中,我將介紹此庫的基礎知識,包括其安裝和用法,並提供一

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境