search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript triggers_javascript skills

The front-end of a website consists of three layers. The structural layer built by XHTML, which includes structured and semantic tags, as well as the content of the website. You can add a presentation layer (CSS) and a behavior layer (JavaScript) on top of this layer, which make the website look more beautiful and more user-friendly. Strict separation should be maintained between these three layers. For example, it should be possible to rewrite the entire presentation layer without touching the structural and behavioral layers.
In addition to this strict separation, both the presentation layer and the behavioral layer need instructions from the structural layer. They have to know where to apply styles and when to initialize behavior - in other words: they need triggers.

Everyone knows about CSS triggers. The class and id attributes give you complete control over the performance of your website. However, you can work without these triggers by using inline style attributes (Translator's Note: Referring to the style="..." attribute written in the XHTML tag), but this usage is It should be strongly opposed. When you want to redefine the performance of your website, you will be forced to change the XHTML structure layer as well. Their presence destroys the separation between performance and structure.

JavaScript Triggers
Behavior layers should work the same way. By moving away from using inline event handlers (such as onmouseover="switchImages('fearful',6,false)"), we can separate behavior from structure. Like CSS, we should use triggers to tell the script where to deploy the behavior.

The simplest JavaScript trigger is the id attribute.

var x = document.getElementById('navigation');if (!x) return;var y = x.getElementsByTagName('a');for (var i=0;i In this way, this script will Triggered by whether id="navigation" appears. If there is no id="navigation", then nothing will happen (if (!x) return); if it appears, then all link elements surrounded by it (referring to a tag) will get a mouseover behavior. This solution is simple, elegant, and works in all browsers. If this method meets your needs, then you don’t need to read any more:)

Advanced Triggers
Unfortunately there are cases where you cannot use ids as triggers:

An id can only appear once in a document, sometimes you may want the same behavior Added to several (or a group of) elements.
Sometimes the script needs more information than just saying "deploy here" (Translator's Note: such as passing some parameters).
We use form scripts to illustrate the above two questions. It can be useful to add form validation triggers to XHTML, such as specifying "this input field (Translator's Note: text input box, password input box, etc.) is required."In order to implement such a trigger, we are likely to get the following script:

function validateForm(){ var x = document.forms[0].elements; for (var i=0;i We What kind of trigger needs to be created to tell this script which input fields are required? Obviously using id will not work: the ideal solution should work with a large number of input fields, and it is natural to think about whether it can be used. class to trigger behavior:

if (x[i].className == 'required' && !x[i].value) //Prompt the user to enter this field
However, strictly speaking , the class attribute is used to define CSS triggers. It is not impossible to define CSS and JavaScript triggers together, but doing so is likely to make the code confusing:

if ( x[i].className.indexOf('required') != -1 && !x[i].value)
In my opinion, the class attribute should only be used in CSS. Class is the main part of the XHTML presentation layer. Triggers will complicate the problem if they are allowed to carry information from the behavior layer. Using class attributes to trigger both layers at the same time conflicts with the separation of behavior and performance, but it is up to you to decide how to do it. Depends.

Messaging Triggers
Additionally, triggers can be more complex than just a command that states "deploy (behavior) here". Sometimes you might want to. Adding a variable to the trigger makes the behavior layer more versatile and can respond to the individual needs of each XHTML element instead of stupidly executing a standard script.

Take a form as an example. , this form includes some text input boxes with an upper limit on string length. The original maxlength attribute no longer works on textarea elements, so we have to write a script to do this. In addition, not all text in this form. The input boxes all have the same maximum string length, so it is necessary to store their respective maximum lengths somewhere.

We hope to have something like this:

. var x = document.getElementsByTagName('textarea');for (var i=0;i max) // notify user of error}
This script requires two key information:

Is there an upper limit on the length of this text input box? This is a very general trigger that tells the script that certain actions should be added here.
What is the upper limit? This is a value that allows the script to correctly check user input.
Here, the class-based approach is no longer appropriate. While it's not technically impossible to do, the code required would become too complex. For example, let's add a trigger to a text input box that has a class called "large" to tell the script that it is required and that the maximum length is 300:


Not only does this mix the presentation layer and the behavior layer, but the script used to read this value will also become weird:

var max = this.className .substring( this.className.indexOf('maxlength') 10);if (this.value.length > max) // Remind the user that something went wrong.
It’s easy to notice that this script only works if we put maxlength=x at the end. If we want this script to handle maxlength=x that is not the last one (this is often the case, for example, if we want to add a value-passing trigger), it will become more complicated.

Problems facing
This is the problem we are facing now. How can we add the perfect JavaScript trigger that allows us to easily pass both a general statement ("Deploy action here") and an element-specific value to the script?

Technically, it is possible to add this information to the class attribute, but the question is is the class designed to do this?

Custom Properties
I turned to another solution. Let's look at the textarea length limit example mentioned earlier. We need two pieces of information:

Is there an upper limit on the length of this text input box?
What is the upper limit?
To express this information in a natural and semantic way requires adding a custom attribute to the textarea:


The maxlength attribute notifies the script to check the user input and pass the attribute's The value passes the maximum length to the script.In the same way, we can change the "required" trigger to a custom attribute. For example: required="true", no matter what value is assigned to it, because it only serves as a notification and does not need to be accompanied by any additional information.


Technically speaking, there is nothing wrong with doing this. W3C DOM's getAttribute() method can read the value of any attribute from any tag. Only Opera versions prior to 7.54 do not allow reading an incorrect attribute (such as src) from a tag (such as

). Fortunately, later versions provide full support for getAttribute().

Here is my solution:

function validateForm(){ var x = document.forms[0].elements; for (var i=0;i max) / / notify user of error}
In my opinion, this solution is easy to implement and consistent with the form of a JavaScript trigger: a "variable name/value" pair provides the name of the trigger and what the script needs value, which also allows you to define behavior for each element individually. Finally, this way of adding triggers to XHTML is fairly simple for beginners.

Custom DTD
But there is another problem here. The page produced with this solution cannot pass the verification. The validator considers required and maxlength to be illegal. Of course, the validator is completely correct to do this. The former attribute does not exist in XHTML, and the latter attribute only belongs to the element.

The solution is to make them legal: define a custom Document Type Definition (DTD), and make a small extension of XHTML to include the attributes we defined. This custom DTD defines the correct location where the new attributes should appear, and then the validator will validate the document according to our custom XHTML flavor. If the DTD says these properties are correct, then they are correct.

If you don’t know how to create a custom DTD, please read this article "Creating a Custom DTD" published by J.David Eisenberg (Translator's Note: Decide whether to translate based on your opinions^_^) , in this article he will tell you all you need to know.

In my opinion, using custom properties to trigger the behavior layer - coupled with a custom DTD that makes these properties legal - can help us separate the behavior layer from the structure layer while maintaining clean code and Efficient script. Furthermore, once these properties and scripts are defined, even the most novice can easily add triggers to XHTML documents.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.