jquery模擬a標籤的click事件,沒法實現跳轉

問題描述

使用jquery模擬a標籤的click事件,沒法觸發其默認行爲。即click()或trigger('click')沒法觸發href跳轉。css

<a id="aBtn" href="https://www.car-me.com/">去卡咪官網</a>
$('#aBtn').click();//沒法跳轉,不生效
$('$aBtn').trigger('click');//一樣沒法跳轉,不生效
複製代碼

問題緣由

jquery內部實現click或trigger方法時,並未真正模擬用戶點擊事件,只是模擬了事件對象及冒泡的觸發。(最後附有jquery實現源碼供參考)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行)

源碼連接地址app

關鍵摘要:dom

// 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;
			}
		}
	}
}
複製代碼
相關文章
相關標籤/搜索