覺得這里的event沒用結(jié)果去掉卻不對$("button:first").click(function(event,bottonName)
<!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>點擊次數(shù)</div> ????????<button>直接點擊</button> ????????<button>通過自定義點擊</button> ????</div> ????<script?type="text/javascript"> ????//點擊更新次數(shù) ????$("button:first").click(function(event,bottonName)?{ ????????bottonName?=?bottonName?||?'first'; ????????update($("span:first"),$("span:last"),bottonName); ????}); ????//通過自定義事件調(diào)用,更新次數(shù) ????$("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沒用 ? 去掉之后結(jié)果變成“[object Object]1點擊次數(shù)”為什么?
2016-10-25
event在這里沒有被使用,但是為什么不能去掉!
首先,要搞清楚.click(function(event,bottonName)在這里做了什么事情
function要傳遞參數(shù)bottonName給 update 函數(shù)
click方法返回了一個事件對象給匿名函數(shù)function,event參數(shù)只是作為接收這個事件對象的一個名稱,改成別的名稱也是可以的,但是這個返回的事件是默認的,必定存在。
當在click里面使用function時,該對象已經(jīng)被添加給了function作為第一參數(shù)了,當我們要繼續(xù)傳遞其他參數(shù)的時候,也必須排在這個參數(shù)之后。
那么我們傳參的時候,必須按順序傳遞給function,即使event不被使用,也需要告訴函數(shù),第一個參數(shù)event是默認用來接收事件對象的,第二個參數(shù)botton才是我們要使用到的參數(shù)。
如果去掉event,函數(shù)就會認為,參數(shù)botton是用來接收事件對象的,這時,當執(zhí)行updata函數(shù)時,該事件對象會作為參數(shù)來使用
那么first.text(bottonName),就會輸出這個對象的類型[[object Object]],而我們實際要傳遞的值,并沒有被傳遞。
2016-09-12
首先event是事件對象,如果$("button:first").click(function(bottonName),function里面就一個參數(shù),這個bottonName就默認是事件對象,就相當于平時寫的e,這是只是變量名,隨便取,知道他代表什么就行了。
如果$("button:first").click(function(event,bottonName),這兩個參數(shù),一個就是事件對象,一個就是自定義變量參數(shù),這里的事件對象沒用到,但在這個代碼中刪掉就會出問題了哦。