Event object discrimination analysis for JS and JQ
- 2020-03-30 04:23:31
- OfStack
Code test:
<div id="test"><p>test text<p></div>
<script src="vendor/jquery-2.1.1.js"></script>
<script>
test.addEventListener('click', function(e){console.log(e);}, false),
$('#test').on('click', function(e){console.log(e)});
</script>
Result analysis:
js-jq-event-common:{
altKey: false,
bubbles: true,
button: 0,
cancelable: true,
clientX: 58,
clientY: 13,
ctrlKey: false,
offsetX: 50,
offsetY: 5,
pageX: 58,
pageY: 13,
screenX: 58,
screenY: 122,
view: Window,
which: 1,
type: 'click',
timeStamp: 1407761742842,
metaKey: false,
relatedTarget: null,
target: div#test
},
js-jq-event-diff:{
currentTarget: null
|| div#test,
eventPhase: 0 || 2,
toElement: div#test
},
js-event-solo:{
x: 58,
y: 13,
cancelBubble: false,
charCode: 0,
clipboardData: undefined,
dataTransfer: null,
defaultPrevented: false,
srcElement: div#test,
fromElement: null,
detail: 1,
keyCode: 0,
layerX: 58,
layerY: 13,
returnValue: true
},
jq-event-solo: {
buttons: undefined,
data: undefined,
delegateTarget: div#test,
isDefaultPrevented: function,
handleObj: Object,
jQuery211024030584539286792: true,
originalEvent: MouseEvent,
shiftKey: false
}
body-click-delegate-event: {
currentTarget: HTMLBodyElement,
delegateTarget: HTMLBodyElement,
target: HTMLDivElement
}
Conclusion:
In the event parameters of js, whether the target, toElement or srcElement are all elements that point to the first trigger event (not bubbling yet), while fromElement is null in the click event. Therefore, if you set the parent event of the parent container containing many elements, then the parent element that triggers the event is likely to be the parent element.
Therefore, in practice, if you want to reference parent, you can only use this
In the event parameter of jq,
CurrentTarget is the element that matches your selector, which is what you want;
DelegateTarget is the element that is listening for the event and belongs to the delegate element
The target in the js event parameter is the first element to trigger the event, which is less useful than currentTarget (not necessarily, as in the bodyclick event)
Some of you might say, well, you're just going to use this to refer to the element that's being triggered by the device, so why bother with currentTarget and target. This idea proves that you're still using jQuery, not tools like Backbone.
Backbone. this is bound to this in many places, so using this in its functions is not allowed:
var view = Backbone.View.extend({
el: document.body,
events: {
'click p': 'showText' //Delegate the body to listen for the click event of p & NBSP; }, < br / >
showText: function(e){
var p = e.currentTarget; // [currentTarget] Gets the element that the selector matches this.log(p.innerHTML); // See, this Don't point to p The element },
log: function(msg){
console.log(msg);
}
});
Although the event objects in JS and JQ are much the same, there are some differences