Home  >  Article  >  Web Front-end  >  JavaScript enhanced custom event event_javascript skills

JavaScript enhanced custom event event_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:21:551053browse
Copy code The code is as follows:

$().ready(function(){
for( var i=0;i<5;i ){
/**
* This way of writing is unprofessional. If it is in a loop, the event will be registered 5 times and the alert will be alerted 5 times after clicking
*/
// $("#aa").click(function(){
// alert(" hahahaha");
// });
/**
* This way of writing is professional. Before registering a click event, first unbind the click event, and then bind a click event, so in the end only one click event is bound
*/
$("#aa").unbind("click");
$("#aa" ).bind("click",function(){
alert("oooooo");
});
}
});

Custom event :
Copy code The code is as follows:

$().ready(function(){
/**
* Custom event, triggered when clicked
*/
$("#aa").bind("click",function(){
//Event trigger, trigger custom event
$( this).trigger("Click me");
});
//Customize a "Click me" event
$("#aa").unbind("Click me");
$("#aa").bind("Click me",function(){
alert("Click me");
});
});

Custom event passing parameters:
Copy code The code is as follows:

$( ).ready(function(){
/**
* Custom event, triggered when clicked
*/
$("#aa").bind("click",function(){
//Event trigger, trigger Custom event, pass actual parameters
$(this).trigger("Click me",['Zhang San','Li Si']);
});
//Customize one "Click me" event
$("#aa").unbind("Click me");
//The first parameter is fixed, and the rest are customized, even if the event is written with another name , it is still a fixed type, mouse event
$("#aa").bind("Click me", function(event,a,b){
alert("Click me");
alert (a);
alert(b);
});
});

Exercise:

Write a custom event and put the event Bind to a drop-down list box

When an item is selected in the drop-down list box, the event is triggered, and the selected value is passed to the custom event in the form of a parameter and output.

html:
Copy code The code is as follows:



js:
Copy code The code is as follows:

$().ready(function(){
$("option").unbind("click");
$(" option").bind("click",function(){
$(this).trigger("Select and display",[$(this).val()]);
});

$("option").unbind("Select and display");
$("option").bind("Select and display",function(event,value){
alert( value);
});

});
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