Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis of event examples in jQuery

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

Most people do not understand the knowledge points of this "event case Analysis in jQuery" article, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "event case Analysis in jQuery" article.

I. Overview:

These methods are used to register the behavior to take effect when the user interacts with the browser, and to further process these registration behaviors.

2. Bind event handler 1, .on ():

Binds one or more event handlers on the selected element.

On (events [, selector] [, data], handler (eventObject))

Example1: when you click on a paragraph, display the text in that paragraph:

$("p") .on ("click", function () {alert ($(this) .text ();})

Example2: pass data into the event handler and get the incoming data by name in the event handler:

Function myHandler (event) {alert (event.data.foo);} $("p") .on ("click", {foo: "bar"}, myHandler)

Example3: cancel the submission action of the form and prevent the event from bubbling by returning false:

("form") .on ("submit", false)

Example4: only the default action is canceled by using .principentDefault ().

("form") .on ("submit", function (event) {event.preventDefault ();})

Example5: prevents bubbling behavior of submitting events by using .stopPropagation (), but does not prohibit submission behavior.

("form") .on ("submit", function (event) {event.stopPropagation ();})

Example6: add and trigger custom events (non-browser events).

On ("myCustomEvent", function (event,myName) {$(this) .text (myName+ ", hithere!"); $("span") .stop () .css ("opacity", 1) .text ("myName=" + myName) .fadeIn (30) .fadeOut (1000);}); $("button") .click (function () {$("p"). Trigger ("myCustomEvent", ["John"]);})

Example7: use objects to add multiple events at the same time

$("div.test") .on ({click: function () {$(this) .toggleClass ("active");}, mouseenter: function () {$(this) .addClass ("inside");}, mouseleave: function () {$(this) .removeClass ("inside";}}); 2, .one ():

Add a handler for the event of the element. Handlers are executed at most once for each event type on each element.

.one (events [, data], handler (eventObject))

.one (events [, selector] [, data], handler (eventObject))

Example1: bind an one-time click event for each div.

Var n = 0 this $("div"). One ("click", function () {var index = $("div"). Index (this); $(this). Css ({borderStyle: "inset", cursor: "auto"}); $("p"). Text ("Div at index #" + index + "clicked." + "That's" + (+ + n) + "total clicks.");})

Example2: when you click on each paragraph for the first time, display the contents of that paragraph:

$("p") .one ("click", function () {alert ($(this) .text ();})

Example3: handlers are executed only once for each event type on each element.

Var n = 0 click mouseenter $(".target") .one ("click mouseenter", function () {$(".count") .html (+ + n); 3, .off ():

Removes an event handler.

.off (events [, selector] [, handler (eventObject)])

Example1: adds and removes event handling for colored buttons.

Function flash () {$("div"). Show (). FadeOut ("slow");} $("# bind") .click (function () {$("body") .on ("click", "# theone", flash) .find ("# theone") .text ("Can Click!");}) $("# unbind") .click (function () {$("body") .off ("click", "# theone", flash) .find ("# theone") .text ("Does nothing...");})

Example2: remove events from all paragraphs:

("p") .off ()

Example3: remove proxy events from all paragraphs:

$("p") .off ("click", "*")

Example4: remove only the previously bound event handlers by passing in the third argument:

Var foo = function () {/ / Code to handle some kind of event}; / / Now foo will be called when paragraphs are clicked... $("body"). On ("click", "p", foo); / /. Foo will no longer be called.$ ("body") .off ("click", "p", foo)

Example5: unbind all proxy events on the form by specifying a namespace:

Var validate = function () {/ / Code to validate form entries}; / / Delegate events under the ".validator" namespace$ ("form"). On ("click.validator", "button", validate); $("form"). On ("keypress.validator", "input [type = 'text']", validate); / / Remove event handlers in the ".validator" namespace$ ("form"). Off (".validator"); 4, .trigger ():

Triggers the specified event type of the selected element.

.trigger (eventType [, extraParameters])

Example1: when clicking button # 2, the click event of button # 1 is triggered at the same time.

$("button"). First (). Click (function () {update ($("span"). First ();}); $("button"). Last (). Click (function () {$("button"). First (). Trigger ("click"); update ($("span"). Last ();}); function update (j) {var n = parseInt (j.text (), 10) J.text (n + 1);}

Example2: to submit the first form without using the submit () function, try the following:

$("form:first") .trigger ("submit")

Example3: to submit the first form without using the submit () function, try the following:

Var event = jQuery.Event ("submit"); $("form") .first () .trigger (event); if (event.isDefaultPrevented ()) {/ / Perform an action...}

Example4: pass arbitrary data into the event:

("p") .click (function (event, a, b) {/ / When a normal click fires, an and b are undefined / / for a trigger like below a refers to "foo" and b refers to "bar"}) .trigger ("click", ["foo", "bar"])

Example5: pass arbitrary data into the event through the event object:

Var event = jQuery.Event ("logged"); event.user = "foo"; event.pass = "bar"; $("body") .trigger (event)

Example6: another way to pass in data through an event object:

$("body") .trigger ({type: "logged", user: "foo", pass: "bar"}); 5, .dispaterHandler ():

An event executes all handlers attached to the element.

.returerHandler (eventType [, extraParameters])

If you use .returerHandler () to trigger the focus event, it will only trigger the handler that binds the event, and the browser's default focus action will not be triggered.

$("# old") .click (function () {$("input"). Trigger ("focus");}); $("# new") .click (function () {$("input"). TriggerHandler ("focus");}); $("input") .focus (function () {$("Focused!"). AppendTo ("body"). FadeOut (1000);}); 6. JQuery.proxy ():

Accepts a function and returns a new function that always maintains a specific context.

JQuery.proxy (function, context [, additionalArguments])

JQuery.proxy (context, name [, additionalArguments])

Example1: modifies the context of click events bound with the jQuery.proxy () method with the parameter "function, context". And after the first click event is executed, the original binding is unbound.

Var me = {type: "zombie", test: function (event) {/ / Without proxy, `this` would refer to the event target / / use event.target to reference that element. Var element = event.target; $(element). Css ("background-color", "red"); / / With proxy, `this` refers to the me object encapsulating / / this function. Append ("Hello" + this.type + "); $(" # test "). Off (" click ", this.test);}}; var you = {type:" person ", test: function (event) {$(" # log "). Append (this.type +");}} / / Execute you.test () in the context of the `you`object// no matter where it is called// i.e. The `this`keyword will refer to `you`var youClick = $.proxy (you.test, you); / / attach click handlers to # test$ ("# test") / / this = = "zombie" Handler unbound after first click .on ("click", $.proxy (me.test, me)) / / this = "person" .on ("click", youClick) / / this = "zombie" .on ("click", $.proxy (you.test, me)) / / this = = "element" .on ("click", you.test)

Example2: forces the context of the function to be modified by calling the jQuery.proxy () method with the argument "context, function name". And unbind after the first click event is executed.

Var obj = {name: "John", test: function () {$("# log") .append (this.name); $("# test") .off ("click", obj.test);}}; $("# test") .on ("click", jQuery.proxy (obj, "test"))

Example3: change the context of the bind click handler function.

Var me = {/ / I'm a dog type: "dog", / / Note that event comes * after* one and two test: function (one, two, event) {$("# log") / / `one`maps to `you`, the 1st additional / / argument in the $.proxy function call .append ("Hello" + one.type + ":") / / The `this`keyword refers to `me` / / (the 2nd, context) Argument of $.proxy) .append ("I am a" + this.type + ",") / `two`maps to `they`, the 2nd additional / / argument in the $.proxy function call .append ("and they are" + two.type + ".") / The event type is "click" .append ("Thanks for" + event.type + "ing.") / / The clicked element is `event.target` / / and its type is "button" .append ("the" + event.target.type + ".") }; var you = {type: "cat"}; var they = {type: "fish"}; / / Set up handler to execute me.test () in the context// of `me`, with `you`they` as additional argumentsvar proxy = $.proxy (me.test, me, you, they); $("# test") .on ("click", proxy); third, browser event 1, .resize ():

Bind a handler for the "resize" event of JavaScript, or trigger the event on the element.

.resize ([eventData], handler (eventObject))

When the window is resized (or changed), view the width of the window:

$(window) .resize (function () {$('body') .prepend (''+ $(window). Width () +'); 2, .resize ():

Bind a handler for the "scroll" event of JavaScript, or trigger the event on the element.

EventData ([eventData], handler (eventObject))

Triggers a series of actions as the page scrolls:

$("p"). Clone (). AppendTo (document.body); $("p"). Clone (). AppendTo (document.body); $("p"). Clone (). AppendTo (document.body); $(window) .documentation (function () {$("span"). Css ("display", "inline"). FadeOut ("slow"); 4. Document loading 1.ready (handler)

Return: jQuery: when DOM is ready, specify a function to execute.

You can use the $(document) .ready () event indefinitely in the same page. The registered functions are executed sequentially (in the code).

Displays information when DOM is loaded.

The ready () method is usually used for an anonymous function:

$(document) .ready (function () {/ / Handler for .ready () called.})

Code:

$(function () {$("p") .text ("The DOM is now loaded and can be manipulated.");}); 2, $.holdReady ():

Pause or resume execution of the .ready () event.

Defer the ready event until the plug-in has been loaded.

$.holdReady (true); $.getScript ("myplugin.js", function () {$.holdReady (false);}); 3, $.ready:

An object similar to promise (or "thenable") that is parsed when the document is ready.

Ready (), which uses this object.

Example1: use jQuery.when to listen for prepared documents.

When ($.ready) .then (function () {/ / Document is ready.})

Example2: typical usage involves another promise, using jQuery.when.

When ($.getJSON ("ajax/test.json"), $.ready) .done (function (data) {/ / Document is ready. / / Value of test.json is passed as `data`}); 5. Form event 1, .blur ():

Bind a handler for the "blur" event, or trigger the "blur" event on the element (note: this event does not support bubbling).

2. Change ([eventData], handler)

Bind a handler for the "change" event of JavaScript, or trigger the "change" event on the element.

Example1: add a change event to the select element to display the selected items in the div.

$("select") .change (function () {var str = "; $(" select option:selected ") .each (function () {str + = $(this). Text () +";}); $("div") .text (str);}) .change ()

Example2: a validity test for adding one to all text input elements:

Change (function () {/ / check input ($(this). Val () for validity here}); 3. Other form events

.focus (): binds a handler for the "focus" event of the JavaScript, or triggers the "focus" event on the element.

.focusin (): binds an event function to the "focusin" event.

.focusout (): binds an event function to the "focusout" event.

.select (): binds a handler for the "select" event of JavaScript, or triggers the event on the element.

Submit (): binds a handler for the "submit" event of JavaScript, or triggers the event on the element.

.submit ([eventData], handler (eventObject))

Example1: if you want to prevent a form from being submitted based on a logo, you can do something like this:

$("form") .submit (function () {if ($("input:first"). Val () = "correct") {$("span") .text ("Validated...") .show (); return true;} $("span") .text ("Not valid!") .show () .fadeOut (1000); return false;})

Example2: if you want to prevent a form from being submitted based on a logo, you can do something like this:

$("form") .submit (function () {return this.some_flag_variable;})

Example3: triggers the submission event of the first form on the page:

$("form:first") .submit (); VI. Keyboard event

.keydown (): binds a handler for the "keydown" event, or triggers the "keydown" event on the element.

.keypress (): binds a handler for the "keypress" event, or triggers the "keypress" event on the element.

.keyup (): binds a handler for the "keyup" event, or triggers the "keyup" event on the element.

.keyup ([eventData], handler (eventObject))

When you release a key in a text box, the event object for the keyup event is displayed. Use a simple $. Print plug-in

Var xTriggered = 0 msg $('# target') .keyup (function (event) {xTriggered++; var msg = 'Handler for. Keyup () called' + xTriggered+ 'time (s).; $.print (msg,' html'); $.print (event);}) .keydown (function (event) {if (event.which = = 13) {event.preventDefault ();}}); $('# other') .click (function () {$('# target'). Keyup () 7. Mouse event 1, .click ():

Bind a handler to the "click" event of the JavaScript, or trigger the "click" event on the element.

.click ([eventData], handler (eventObject))

Example1: hide them when you click on them:

$("p") .click (function () {$(this) .slideUp ();})

Example2: the click event is triggered on all paragraphs on the page.

$("p"). Click (); 2. Other mouse events

.contextmenu (): binds a handler for the "contextmenu" event of JavaScript, or triggers the "contextmenu" event on the element.

.dblclick (): binds a handler for the "dblclick" event of JavaScript, or triggers the "dblclick" event on the element.

.hover (): binds two event functions to a matching element, which is executed when the mouse pointer enters and leaves the element, respectively. Bind a separate event function to the matching element, which is executed when the mouse pointer enters and leaves the element, respectively.

.mousedown (): binds a handler for the "mousedown" event of JavaScript, or triggers the event on the element.

Mouseenter (): binds a handler for the mouse enters (mouse entry) event, or triggers the mouse enters (mouse entry) event on the element.

.mouseleave (): binds a handler for the mouse leaves (mouse away) event, or triggers the mouse leaves (mouse away) event on the element.

.mousemove (): binds a handler for the "mousemove" event of JavaScript, or triggers the event on the element.

.mouseout (): binds a handler for the "mouseout" event of JavaScript, or triggers the event on the element. (note: event bubbling is supported)

.Mouseover (): binds a handler for the "mouseover" event of JavaScript, or triggers the event on the element. (note: event bubbling is supported)

.mouseup (): binds a handler for the "mouseup" event of JavaScript, or triggers the event on the element.

8. Event object 1, attribute list:

MetaKey: indicates which Meta key is pressed when the event is triggered.

PageX, pageY: the position (coordinates) of the mouse relative to the left edge and top edge of the document.

RelatedTarget: any other DOM elements involved in the event.

Target: the DOM element that triggers the event.

Which: for keyboard and mouse events, this property determines which key you press.

Type: describes the nature of the event.

CurrentTarget: the current DOM element in the event bubbling process.

Data: when the currently executing handler is bound, an optional data object is passed to an event method.

DelegateTarget: binds the element that is currently calling the jQuery event handler.

Namespace: this property contains the specified namespace when the event is triggered.

Result: the last return value of an event handler that triggered the event, unless the value is undefined.

TimeStamp: this property returns the number of milliseconds from January 1, 1970 when the event was triggered.

Some events may have their specific properties. Those properties can be accessed on the event.originalEvent object.

/ / add the dataTransfer property for use with the native `drop` event// to capture information about files dropped into the browser windowjQuery.event.props.push ("dataTransfer"); 2. Function list:

Event.isDefaultPrevented (): returns a Boolean value depending on whether the event.preventDefault () method has been called in the event object.

Event.isImmediatePropagationStopped (): returns a Boolean value depending on whether the event.stopImmediatePropagation () method has been called in the event object.

Event.isPropagationStopped (): returns a Boolean value depending on whether the event.stopPropagation () method has been called in the event object.

Event.preventDefault (): if this method is called, the default event behavior will no longer be triggered.

Event.stopImmediatePropagation (): prevents the execution of the remaining event handlers and prevents events from bubbling onto the DOM tree.

Event.stopPropagation (): event handlers that prevent events from bubbling onto the DOM tree, that is, on any predecessor elements that are not triggered.

Record button:

$('# whichkey'). Bind ('keydown',function (e) {$(' # log') .html (e.type +':'+ e.which);}). The above is about the content of the article "event case Analysis in jQuery". I believe you all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report