1. 程式人生 > >jquery模擬a標籤的click事件,無法實現跳轉

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事件或利用事件冒泡來解決。

  1. 原生dom觸發click
<a id="aBtn" href="https://www.car-me.com/">去卡咪官網</a>
document.querySelector('#aBtn').click();//原生dom觸發 或者
$('#aBtn')[0].click();//jquery物件轉為dom物件再觸發
複製程式碼
  1. 利用子元素事件冒泡
<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;
			}
		}
	}
}
複製程式碼