<!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="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
????</script>
</head>
<body>
<h2>自定義事件triggerHandler</h2>
<div?class="left">
????<div?id="accident">
????????<a>triggerHandler事件</a>
????????<form?name="input"?action=""?method="get">
??????????<input?type="text"?value="momomo">
????????</form>
????</div>
????<button>事件冒泡,觸發(fā)瀏覽器默認(rèn)聚焦行為</button><br><br>
????<button>不會(huì)冒泡,不觸發(fā)瀏覽器默認(rèn)聚焦行為</button>
</div>
<script?type="text/javascript">
????//給input綁定一個(gè)聚焦事件
????var?n=0;
????$("#accident").on("mouseenter",function(event,title)?{
????????title=title||"默認(rèn)";
????????$("input").val(++n);
????});
????$("#accident").on("click",function(e)?{
????????alert("trigger觸發(fā)的事件會(huì)在?DOM?樹中向上冒泡");
????});
????//trigger觸發(fā)focus
????$("button:first").click(function()?{
????????$("a").trigger("click");
????????$("input").trigger("mouseenter","傳遞");
????});
????//triggerHandler觸發(fā)focus
????$("button:last").click(function()?{
????????$("a").triggerHandler("click");
????????$("input").triggerHandler("mouseenter","沒有觸發(fā)默認(rèn)聚焦事件");
????});
</script>
</body>
</html>
2017-12-09
在jquery的trigger源碼中:
type 是事件類型。
eventPath就是從target 到window對(duì)象 的一條路徑。
當(dāng)event.isPropagationStopped() 為假時(shí),會(huì)遍歷eventPath,調(diào)用每個(gè)符合的jquery處理器。
從源碼上知道, type='mouseenter' ?ontype = 'onmouseenter'。必然分別調(diào)用Jquery,原生接口中的處理函數(shù)。
在原生接口中,對(duì)應(yīng)event[ontype]
jquery接口中,對(duì)應(yīng)dataPri.get(cur,'events')[type] ?或者dataPriv.get(cur,'handle') 。
而elem.on() 函數(shù)的調(diào)用:elem.on() -> jquery.on() -> event.add() 最終添加到隊(duì)列中。