11

Why can not I trigger the default href on another anchor with JS?

 3 years ago
source link: https://www.codesd.com/item/why-can-not-i-trigger-the-default-href-on-another-anchor-with-js.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Why can not I trigger the default href on another anchor with JS?

advertisements

I'm posting this because I can't find the same question elsewhere.

I'm trying to trigger the default action of an anchor but calling .click() or .trigger('click') in the click handler of another anchor.

Like so:

HTML:

<!-- I want to simulate a user clicking link2 when the user actually clicks link 1. -->
<!-- My guess is that triggering click just triggers any JS-bound click handlers. But that would defeat the point of e.preventDefault() when you usually have to call this to stop the default href being followed -->
<a id="link1" href="#">Click</a>
<a id="link2" target="_blank" href="http://google.com">Link 2</a>

    $(document).ready(function(){
         $('#link1').on('click', function(){
              $('#link2').click();
              $('#link2').trigger('click'); // Neither work
         });
    });

I feel like such a noob but nothing happens on click. Is this something that is blocked for security or accessibility?

I do not want to use window.open();

fiddle: http://jsfiddle.net/0hggdkzb/


jQuery(document).ready(function(){
    $('#link1').on('click', function(){
      // $('#link2').click().css('color','red');
        document.getElementById("link2").click();
    });
});

DEMO

you can trigger event $('#link2')[0].click();


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK