Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

javascript - Why jQuery cannot trigger native click on an anchor tag?

Recently I found jQuery cannot trigger the native click event on an anchor tag when I'm clicking on other elements, the example below won't work:

html

<a class="js-a1" href="new.html" target="_blank">this is a link</a>
<a class="js-a2" href="another.html" target="_blank">this is another link</a>

javascript

$('.js-a1').click(function () {
  $('.js-a2').click();
  return false;
});

And here is the jsfiddle - 1. Click on the first link won't trigger native click on the second one.

After some searches, I found a solution and an explanation.

Solution

Use the native DOM element.

$('.js-a1').click(function () {
  $('.js-a2').get(0).click();
  return false;
});

And here is the jsfiddle - 2.

Explanation

I found a post on Learn jQuery: Triggering Event Handlers. It told me:

The .trigger() function cannot be used to mimic native browser events, such as clicking on a file input box or an anchor tag. This is because, there is no event handler attached using jQuery's event system that corresponds to these events.

Question

So here comes my question:

How to understand 'there is no event handler attached using jQuery's event system that corresponds to these events'?

Why is there not such corresponding event handler?

EDIT

I update my jsfiddles, it seems there's and error on the class name.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

there is no event handler attached using jQuery's event system that corresponds to these events

This means, at this point of the learning material, no jQuery event handlers has been attached to these elements using .click(function() {} or .bind('click', function () {}), etc.

The no-argument .click() is used to trigger (.trigger('click')) a "click" event from jQuery's perspective, which will execute all "click" event handlers registered by jQuery using .click, .bind, .on, etc. This pseudo event won't be sent to the browser.

.trigger()

Execute all handlers and behaviors attached to the matched elements for the given event type.

Check the updated jsFiddle example, click on the two links to see the difference. Hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...