2016-12-15 48 views
0

我正在做事件定位實驗並在香草JS和jQuery中比較它的執行情況。我很驚訝,結果是不同的;它在香草JS中取得了成功,但在jQuery中卻不成功。如果我沒有弄錯,jQuery中的事件定位代碼是$(event.target),而vanilla JS中的代碼是event.target。在我的實驗中,我只在<body>標籤內有一個按鈕,並且每當它被某個事件定位時,瀏覽器都會提示「按鈕元素是目標」,否則它將是「窗口本身是有針對性的」。但是,即使目標元素是按鈕,警報通知也只是「窗口本身有針對性」。這裏是我的代碼:在香草JS和jQuery中針對事件定位

香草JS

let $ = document.querySelector.bind(document); 

window.onclick = function(event) { 
    if(event.target != $('button')) { 
     alert('window itself is targeted'); 
    } else { 
     alert('button element is targeted'); 
    } 
} 

jQuery的

$(window).on('click', function(event) { 
    var $eventTarget = $(event.target); 

    if($eventTarget != $('button')) { 
     alert('window itself is targeted'); 
    } else { 
     alert('button element is targeted'); 
    } 
}); 

在jQuery代碼,我試圖用event.target更換$(event.target),看看它的執行將類似於香草JS,但沒有任何改變。它是我的代碼的語法,使它失敗或有什麼其他錯誤,我只是沒有注意到。我希望有人能夠向我指出。

回答

2

因爲$('button')$(event.target),即使它們引用相同的Button,它們也不是相同的Object。

正確的方法使用jQuery是比較它們的標籤/班/ ID或任何其他屬性

alert($(event.target) == $(event.target)); // false (same target, different jQuery objects) 

alert($('button') == $('button')); // false (same button, different jQuery objects) 

alert($(event.target).is('button')); // true (comparing element tags) 

alert($(event.target).attr('id') == 'buttonId'); // true (comparing element ids) 

alert($(event.target).hasClass('buttonClass')); // true (comparing element classes) 

DEMO

+0

感謝很多:) – jst16

+0

所以'是()'方法是解決 – jst16

+0

@ jst16它的一個解決方案(其中你比較的元素的HTML標籤) 。您還可以比較類,ID或任何其他屬性 –

2

您的測試是有缺陷的event.target != $('button')將永遠是爲真正的比較兩個DOM元素你正在比較一個DOMElement和一個jQuery對象,並且$eventTarget != $('button')也會一直如此,因爲你不能直接比較對象。

爲了解決這個問題比較性能對象

// Native: 
let $ = document.querySelector.bind(document); 
window.addEventListener('click', function(e) { 
    if (e.target.id != $('button').id) { 
     alert('window itself is targeted'); 
    } else { 
     alert('button element is targeted'); 
    } 
}); 

注意使用的優選addEventListener()這裏,過onclick()

Working native example

// jQuery 
$(window).on('click', function(e) { 
    if (e.target.id != $('button').prop('id')) { 
     alert('window itself is targeted'); 
    } else { 
     alert('button element is targeted'); 
    } 
}); 

Working jQuery example