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