Home  >  Article  >  Web Front-end  >  JavaScript加强之自定义event事件_javascript技巧

JavaScript加强之自定义event事件_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:21:55970browse
复制代码 代码如下:

$().ready(function(){
for(var i=0;i/**
* 这种写法不专业,如果处于循环里,就会注册5次事件,点击后alert5次
*/
// $("#aa").click(function(){
// alert("hahahaha");
// });
/**
* 这种写法才是专业的,在注册一次点击事件前,先解绑点击事件,然后再绑定一个点击事件,所以到最后只绑定了一次点击事件
*/
$("#aa").unbind("click");
$("#aa").bind("click",function(){
alert("oooooo");
});
}
});

自定义事件:
复制代码 代码如下:

$().ready(function(){
/**
* 自定义事件,在click的时候进行触发
*/
$("#aa").bind("click",function(){
//事件触发器,触发自定义的event
$(this).trigger("点我");
});
//自定义一个"点我"事件
$("#aa").unbind("点我");
$("#aa").bind("点我",function(){
alert("点我");
});
});

传递参数的自定义事件:
复制代码 代码如下:

$().ready(function(){
/**
* 自定义事件,在click的时候进行触发
*/
$("#aa").bind("click",function(){
//事件触发器,触发自定义的event,传递实参
$(this).trigger("点我",['张三','李四']);
});
//自定义一个"点我"事件
$("#aa").unbind("点我");
//第一个参数是固定的,后面都是自定义,就算把event写成别的名字,它还是固定类型,鼠标事件
$("#aa").bind("点我",function(event,a,b){
alert("点我");
alert(a);
alert(b);
});
});

练习:

写一个自定义事件,把该事件绑定在一个下拉列表框中

当下拉列表框选中一项的时候,触发该事件,以参数的形式把选中的值传递到自定义事件中,并输出。

html:
复制代码 代码如下:



js:
复制代码 代码如下:

$().ready(function(){
$("option").unbind("click");
$("option").bind("click",function(){
$(this).trigger("选择并显示",[$(this).val()]);
});

$("option").unbind("选择并显示");
$("option").bind("选择并显示",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