啊啊啊啊123
2016-09-09 10:29
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title></title>
<style>
.left div,
.right div {
width: 500px;
height: 50px;
padding: 5px;
margin: 5px;
float: left;
border: 1px solid #ccc;
}
.left div {
background: #bbffaa;
}
.right div {
background: yellow;
}
</style>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.js"></script>
</head>
<body>
<h2>自定义事件trigger</h2>
<div class="left">
<div><span></span><span>0</span>点击次数</div>
<button>直接点击</button>
<button>通过自定义点击</button>
</div>
<script type="text/javascript">
//点击更新次数
$("button:first").click(function(event,bottonName) {
bottonName = bottonName || 'first';
update($("span:first"),$("span:last"),bottonName);
});
//通过自定义事件调用,更新次数
$("button:last").click(function() {
$("button:first").trigger('click','last');
});
function update(first,last,bottonName) {
first.text(bottonName);
var n = parseInt(last.text(), 10);
last.text(n + 1);
}
</script>
</body>
</html>$("button:first").click(function(event,bottonName)觉得这里的event没用 去掉之后结果变成“[object Object]1点击次数”为什么?
$("button:first").click(function(event,bottonName){
bottonName = bottonName || 'first';
update($("span:first"),$("span:last"),bottonName);
});event在这里没有被使用,但是为什么不能去掉!
首先,要搞清楚.click(function(event,bottonName)在这里做了什么事情
function要传递参数bottonName给 update 函数
click方法返回了一个事件对象给匿名函数function,event参数只是作为接收这个事件对象的一个名称,改成别的名称也是可以的,但是这个返回的事件是默认的,必定存在。
当在click里面使用function时,该对象已经被添加给了function作为第一参数了,当我们要继续传递其他参数的时候,也必须排在这个参数之后。
那么我们传参的时候,必须按顺序传递给function,即使event不被使用,也需要告诉函数,第一个参数event是默认用来接收事件对象的,第二个参数botton才是我们要使用到的参数。
如果去掉event,函数就会认为,参数botton是用来接收事件对象的,这时,当执行updata函数时,该事件对象会作为参数来使用
function update(first,last,bottonName) {
first.text(bottonName);
var n = parseInt(last.text(), 10);
last.text(n + 1);
}那么first.text(bottonName),就会输出这个对象的类型[[object Object]],而我们实际要传递的值,并没有被传递。
首先event是事件对象,如果$("button:first").click(function(bottonName),function里面就一个参数,这个bottonName就默认是事件对象,就相当于平时写的e,这是只是变量名,随便取,知道他代表什么就行了。
如果$("button:first").click(function(event,bottonName),这两个参数,一个就是事件对象,一个就是自定义变量参数,这里的事件对象没用到,但在这个代码中删掉就会出问题了哦。
jQuery基础(三)—事件篇
89984 学习 · 645 问题
相似问题