In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces "how to achieve interaction between JavaScript and HTML". In daily operation, I believe many people have doubts about how to achieve interaction between JavaScript and HTML. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "how to interact between JavaScript and HTML". Next, please follow the editor to study!
The interaction between JavaScript and HTML is achieved through events. JavaScript uses an asynchronous event-driven programming model in which browsers generate events when specific things happen to documents, browsers, elements, or related objects. If JavaScript is concerned with a particular type of event, it can register the handle to be called when such an event occurs.
Event flow
The event flow describes the order in which events are received from the page. For example, there are two nested div that clicks on the inner div. At this time, does the inner div start the click event first or trigger the outer layer first? At present, there are three main models.
Event bubbling of IE: the event is received by the most specific element at the beginning, and then propagated up to the less specific element
Netscape event capture: less specific nodes receive events earlier, while the most specific elements end up receiving events, as opposed to event bubbles
DOM event flow: the DOM2 level event defines that the event flow consists of three stages, the event capture stage, the target stage and the event bubbling stage. The first occurrence is the event capture, which provides the opportunity to intercept the event, then the actual target receives the event, and finally the bubbling sentence stage.
Opera, Firefox, Chrome and Safari all support DOM event flow. IE does not support event flow, but only supports event bubbling.
If you have the following html, click on the div area
Copy the code
Test Page
Click Here
Copy the code
Untitled
Untitled
Untitled
Event bubbling model
Event capture model
DOM event flow
Event handler (handler)
Also known as an event listener (listener), an event is an action performed by the user or the browser itself. For example, click, load, moseover, etc., are all event types (commonly known as event names), and the methods that respond to an event are called event handlers or event listeners or event handlers, and the event handler name is: on+ event type.
With this in mind, let's take a look at how to add event handlers to elements
HTML event handler
Each event supported by the element can be specified using a HTML attribute with the same name as the corresponding event handler. The value of this property should be executable JavaScript code, and we can add a click event handler to a button
Function showMessage () {
Alert ('Clickedlings')
}
Specifying event handlers for writing in HTML is convenient, but has two drawbacks.
First of all, there is a problem with the loading order. If the event handler is loaded after the html code, the user may click on a trigger event such as a button before the event handler is loaded, resulting in a time lag.
Secondly, writing html code and JavaScript code in this way is closely coupled, so it is not convenient to maintain.
JavaScript specifies the event handler
To specify an event handler through JavaScript is to assign a method to the event handler property of an element. Each element has its own event handler properties, whose names are usually lowercase, such as onclick, etc. You can specify an event handler by setting the value of these attributes to a method, as follows
Copy the code
Var btnClick = document.getElementById ('btnClick')
BtnClick.onclick = function showMessage () {
Alert (this.id)
}
Copy the code
In this way, the event handler is considered to be the method of the element, the event handler runs under the scope of the element, and this is the current element, so click button and the result is: btnClick
Another advantage of this is that we can delete the event handler by assigning the element's onclick attribute to null.
DOM2 event handler
DOM2-level events define two methods for handling operations that specify and delete event handlers: addEventListener and removeEventListener. All DOM nodes contain these two methods, and they all accept three parameters: the event type, the event handling method, and a Boolean value. The final Boolean parameter, if true, indicates that the event handler is called during the capture phase, and if it is false, it is handled during the event bubbling phase.
We can write about the example just now.
Copy the code
Var btnClick = document.getElementById ('btnClick')
BtnClick.addEventListener ('click', function () {
Alert (this.id)
}, false)
Copy the code
The above code adds a handler for the click event to button, which is triggered during the bubbling phase. Like the previous method, this program also runs in the scope of the element, but with the advantage that we can add multiple handlers to the click event.
Copy the code
Var btnClick = document.getElementById ('btnClick')
BtnClick.addEventListener ('click', function () {
Alert (this.id)
}, false)
BtnClick.addEventListener ('click', function () {
Alert ('Hellobirds')
}, false)
Copy the code
The two event handlers are executed in the order in which they are added after the user clicks button.
Event handlers added through addEventListener can only be removed through removeEventListener, with the same parameters as when they are added, which means that the anonymous function we just added cannot be removed, because the anonymous function has the same method, but the handle is different, so we can write this when we have a remove event handler.
Copy the code
Var btnClick = document.getElementById ('btnClick')
Var handler=function () {
Alert (this.id)
}
BtnClick.addEventListener ('click', handler, false)
BtnClick.removeEventListener ('click', handler, false)
Copy the code
Here are the platitudes of IE compatibility issues.
Instead of supporting the addEventListener and removeEventListener methods, IE implements two similar methods, attachEvent and detachEvent, both of which receive two identical parameters, the event handler name and the event handler method. Because IE means supporting event bubbling, the added program is added to the bubbling phase.
Using attachEvent to add event handlers can be as follows
Copy the code
Var btnClick = document.getElementById ('btnClick')
Var handler=function () {
Alert (this.id)
}
BtnClick.attachEvent (
'onclick'
, handler)
Copy the code
The result is undefined, which is strange, and we'll talk about it in a moment.
Event handlers added with attachEvent can be removed via detachEvent, with the same parameters, and anonymous functions cannot be removed.
Copy the code
Var btnClick = document.getElementById ('btnClick')
Var handler=function () {
Alert (this.id)
}
BtnClick.attachEvent ('onclick', handler)
BtnClick.detachEvent ('onclick', handler)
Copy the code
Cross-browser event handler
As we can see, there are different ways to add and remove event handlers in different browsers. In order to write cross-browser event handlers, we first need to understand the differences in handling event handlers in different browsers.
There are several main differences between addEventListener and attachEvent when adding event handlers
1. The number of parameters is different, which is the most intuitive. AddEventListener has three parameters and attachEvent has only two. Event handlers added by attachEvent can only occur in the bubbling phase. The third parameter of addEventListener can determine whether the added event handlers are handled in the capture phase or bubbling phase (we usually set them to bubbling phase for browser compatibility).
two。 The meaning of the first parameter is different. The first parameter of addEventListener is the event type (such as click,load), while the first parameter of attachEvent indicates the name of the event handler (onclick,onload).
3. The scope of the event handler is different. The scope of addEventListener is the element itself, this refers to the trigger element, and the attachEvent event handler runs in the global variable, and this is window. That's why the example just returned undefined instead of the element id.
4. When adding multiple event handlers for an event, the execution order is different, and addEventListener addition will be executed in the order of adding multiple event handlers, while attachEvent adds multiple event handlers in an irregular order (when adding fewer methods, it is mostly in the reverse order of adding, but adding more is irregular), so when adding more than one, it is better not to rely on the execution order, if it depends on the function execution order. You'd better handle it yourself and don't count on the browser.
After understanding these four differences, we can try to write a method of adding event handlers with good browser compatibility.
Copy the code
Function addEvent (node, type, handler) {
If (! node) return false
If (node.addEventListener) {
Node.addEventListener (type, handler, false)
Return true
}
Else if (node.attachEvent) {
Node.attachEvent ('on' + type, handler,)
Return true
}
Return false
}
Copy the code
In this way, first of all, we have solved the first problem with a different number of parameters. now the three parameters are triggered by the event bubbling phase, and the second problem can also be solved. if it is IE, we add on to type, and the fourth problem has not been solved yet, which requires the attention of users themselves. In general, people will not add many event handlers. It feels good to try this method. But we did not solve the third problem, because the scope of the handler is different, if there are operations such as this in handler, then there will be errors under IE, in fact, most functions will have this operations.
Copy the code
Function addEvent (node, type, handler) {
If (! node) return false
If (node.addEventListener) {
Node.addEventListener (type, handler, false)
Return true
}
Else if (node.attachEvent) {
Node.attachEvent ('on' + type, function () {handler.apply (node);})
Return true
}
Return false
}
Copy the code
This can solve the problem of this, but there is a new problem. We have added an anonymous event handler, and we cannot cancel the event handler with detachEvent. There are many solutions, and we can learn from the master's way of dealing with it. John Resig, founder of jQuery, does this.
Copy the code
Function addEvent (node, type, handler) {
If (! node) return false
If (node.addEventListener) {
Node.addEventListener (type, handler, false)
Return true
}
Else if (node.attachEvent) {
Node ['e' + type + handler] = handler
Node [type + handler] = function () {
Node ['e' + type + handler] (window.event)
}
Node.attachEvent ('on' + type, node [type + handler])
Return true
}
Return false
}
Copy the code
When canceling the event handler
Copy the code
Function removeEvent (node, type, handler) {
If (! node) return false
If (node.removeEventListener) {
Node.removeEventListener (type, handler, false)
Return true
}
Else if (node.detachEvent) {
Node.detachEvent ('on' + type, node [type + handler])
Node [type + handler] = null
}
Return false
}
Copy the code
John Resig takes advantage of closures very cleverly and looks good.
Event object
When an event is triggered on the DOM, an event object event is generated, which contains all the information related to the event, including the element that generated the event, the type of event, and so on. All browsing supports event objects, but in different ways.
Event objects in DOM
DOM-compliant browsers generate an event object that is passed into the event handler. Apply the addEvent method we just wrote.
Var btnClick = document.getElementById ('btnClick')
AddEvent (btnClick, 'click', handler)
When we click on button, we can see that the pop-up content is the pop-up window of click.
The event object contains properties and methods related to the specific event that created it. The type of event that triggers it is different, and the available properties and methods are different, but all events contain
Attribute / method
Types
Read / write
Description
Whether the bubbles Boolean read-only event is bubbling
Can cancelable Boolean read-only cancel the default behavior of an event
The currentTarget Element read-only event handler currently handles elements
Detail Integer reads only event-related details
EventPhase Integer read-only event handler phase: 1 capture phase, 2 target phase, 3 bubbling phase
PreventDefault () Function read-only cancel event default behavior
StopPropagation () Function read-only cancel event further captures or bubbles
Target element of the target Element read-only event
Type String read-only event types triggered
View AbstractView reads only the abstract view associated with the event, which is equivalent to the window object in which the event occurred
Within the event handler, this is always equivalent to currentTarget, and target is the actual target of the event.
To block the default behavior of an event, you can use the preventDefault () method, provided that the cancelable value is true, for example, we can block the default behavior of link navigation
Document.getElementsByTagName ('a'). Onclick = function (e) {
E.preventDefault ()
}
The stopPaopagation () method stops the propagation of events at the DOM level, that is, canceling further event capture or bubbling. We can call stopPropagation () in the event handler of button to avoid events registered on body.
Copy the code
Var handler = function (e) {
Alert (e.type)
E.stopPropagation ()
}
AddEvent (document.body, 'click', function () {alert (' Clicked body')})
Var btnClick = document.getElementById ('btnClick')
AddEvent (btnClick, 'click', handler)
Copy the code
If you comment out e.stopPropagation (); when you click button, the click event of body will also be triggered because the event bubbles, but after calling this sentence, the event will stop propagating.
Event objects in IE
There are several different ways to access the event object in IE, depending on how you specify the event handler. When you add an event handler directly to a DOM element, the event object exists as an attribute of the window object.
Copy the code
Var handler = function () {
Var e = window.event
Alert (e.type)
}
Var btnClick = document.getElementById ('btnClick')
BtnClick.onclick = handler
Copy the code
We got the event object through window.event and detected its type, but if the event handler was added through attachEvent, then an event object would be passed into the event handler
Var handler = function (e) {
Alert (e.type)
}
Var btnClick = document.getElementById ('btnClick')
AttachEvent (btnClick, handler)
Of course, you can also access event through the window object at this time. For convenience, we usually pass in the event object, and all events in IE contain the following property methods
Attribute / method
Types
Read / write
Description
CancelBulle Boolean read / write defaults to false, and event bubbling can be canceled when set to true
ReturnValue Boolean read / write defaults to true, and setting it to false cancels the default behavior of events
Target element of the srcElement Element read-only event
Type String read-only event types triggered
Cross-browser event object
Although the event objects of DOM and IE are different, we can still write a cross-browser event object scheme based on their similarity.
Copy the code
Function getEvent (e) {
Return e | | window.event
}
Function getTarget (e) {
Return e.target | | e.scrElement
}
Function preventDefault (e) {
If (e.preventDefault)
E.preventDefault ()
Else
E.returnValue = false
}
Function stopPropagation (e) {
If (e.stopPropagation)
E.stopPropagation ()
Else
E.cancelBubble = true
}
Copy the code
Common HTML events
There are some HTML events we will often use, these events are not necessarily related to user operations, here is only a brief mention, detailed usage, we have to Baidu Google
Load: triggered on the window when the page is fully loaded, on the img element when the image is loaded, or on the object element when the embedded content is loaded
Unload: triggered on the window after the page is completely unloaded, or triggered on the object element after the embedded content is unloaded
Select: triggered when the user selects a character in the text box
Change: triggered when the value of a text box changes after its focus changes
Submit: triggered when a user submits a form
Resize: triggered on window when window or frame size changes
Scrool: triggered on an element with a scroll bar when the user scrolls it
Focus: triggered on window and corresponding elements when a page or element gains focus
Blur: triggered on window and corresponding elements when a page or element loses focus
Beforeunload: triggered on window before the page is unloaded
Mousewheel: not counting HTML, triggered when the user interacts with the page through the mouse wheel and scrolls the page vertically
At this point, the study on "how to interact with JavaScript and HTML" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.