Why does the click () method in jQuery behave differently than the click () DOM method?

I'm tired of simulating a click event for a child element to trigger its click event, and its parent element also has a click event. At first, I thought I could do this:

document.getElementById('child').click();

or in jquery

$('#child').click();

However, I later discovered that these two methods behave differently.

The dom method fires the click event as expected, but the jquery method fires the click event of the parent element twice.

Here is an example on a violin. https://jsfiddle.net/5t5jc7ey/

Can someone explain why jquery fires twice for a parent click event?

+4
source share
3 answers

, , - , , , . e.preventDefault();

. :

$('#jquery').click(function() {
  $('#child').click(function(e){e.preventDefault();}).click();
});

$('#dom').click(function() {
  document.getElementById('child').click();
});

:

1. - .

  1. , , div. e.preventDefault();

, , .

+1

breakpoint/debugger , .

, Chrome:

j…y.Event {type: "click", timeStamp: 1467985074919, jQuery2240856213100863372: true, isTrigger: 3, namespace: ""…}
    isTrigger : 3
    jQuery2240856213100863372 : true
    namespace : ""
    result : undefined
    rnamespace : null
    target : div#child
    timeStamp : 1467985074919
    type : "click"
    __proto__ : Object

, , . , jQuery "click" .

.

MouseEvent {isTrusted: false, screenX: 0, screenY: 0, clientX: 0, clientY: 0…}
    altKey : false
    bubbles : true
    button : 0
    buttons : 0
    cancelBubble : false
    cancelable : true
    ....

, -, mouseclick, 3 () . , jquery.

, mouseevent jQuery = .

, "", , .

0

Your trigger applies to parent elements. To prevent the possibility of a use event.stopPropagation()that stops bubbling events to parent elements, preventing any parent event handlers from executing.

Take this example:

HTML:

<p><a id="someId">Text</a></p>

JS:

$('p').click(function(event){
    something();
})
$('#someId').click(function(event){
    event.stopPropagation();
    somethingElse();
})

In the above example, clicking a link #someIdwill trigger something(), but not somethingElse(), due to use event.stopPropagation().

-1
source

All Articles