使用jquery模拟a标签的click事件无法实现跳转的解决
问题描述
最近在使用jquery模拟a标签的click事件,无法触发其默认行为。即click()
或trigger('click')
无法触发href跳转。
<a id="aBtn" href="https://www.car-me.com/">去卡咪官网</a> $('#aBtn').click();//无法跳转,不生效 $('$aBtn').trigger('click');//同样无法跳转,不生效
下面就来一起分析下其原因与解决方法吧
问题原因
jquery内部实现click或trigger方法时,并未真正模拟用户点击事件,只是模拟了事件对象及冒泡的触发。(最后附有jquery实现源码供参考)
解决方案
解决思路:在原生dom触发click事件或利用事件冒泡来解决。
原生dom触发click
<a id="aBtn" href="https://www.car-me.com/">去卡咪官网</a> document.querySelector('#aBtn').click();//原生dom触发 或者 $('#aBtn')[0].click();//jquery对象转为dom对象再触发
利用子元素事件冒泡
<a id="aBtn" href="https://www.car-me.com/"> <span id="spanBtn">去卡咪官网</span> </a> $('#spanBtn').click();//或者 $('#spanBtn').trigger('click');
jquery trigger()实现源码(8159行-8304行)
关键摘要:
// Fire handlers on the event path (8237行) i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { lastElement = cur; event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { //******自身trigger('click')或click()时,会调用缓存列表里的事件回调函数,但未执行elem.click()****** handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } }
// If nobody prevented the default action, do it now (8263行) if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; if ( event.isPropagationStopped() ) { lastElement.addEventListener( type, stopPropagationCallback ); } //******子元素trigger('click')或click(),会执行elem.click()****** elem[ type ](); if ( event.isPropagationStopped() ) { lastElement.removeEventListener( type, stopPropagationCallback ); } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } }
总结