jQuery: trigger click() doesn't work?

前端 未结 6 633
面向向阳花
面向向阳花 2020-12-05 20:28

Why clicking on trigger1 and trigger2 doesn\'t fire click on open ?



        
6条回答
  •  遥遥无期
    2020-12-05 21:12

    From what your code looks like, you want when a user clicks on link one or two (trigger 1 or 2) you want the link in open to be followed?

    If this is the case, .click() isn't actually the function you want, in fact jQuery doesn't seem to offer a method of directly clicking on an anchor element. What it will do is trigger any event's which are attached to an element.

    Take a look at this example:

    trigger
    open
    

    jQuery:

    $('#open').click(function(){
        alert('I just got clicked!'); 
    });
    

    Try it here

    So there is an event attached to the element with the ID open that simply alerts to say it was clicked. Clicking on the trigger link simply triggers the click event on the element with the ID open. So it's not going to do what you want! It will fire any events but it won't actually follow the link
    I removed the 2nd trigger because .click() is just a proxy for .trigger('click') so they do the same thing!

    So to trigger an actual click on an anchor, you will have to do a little more work. To make this slightly more reuseable I would change your HTML a little (I'll expain why in a moment):

    trigger google
    google
    

    trigger bing bing

    jQuery (shortest):

    $('.trigger').click(function(e){
        e.preventDefault();
        window.location = $($(this).attr('rel')).attr('href');
    });
    

    Try it here

    OR:

    $('.trigger').click(function(e){
        e.preventDefault();
        var obj = $(this).attr('rel');
        var link = $(obj).attr('href');
        window.location = link;
    });
    

    Try it here

    Basically any link you want to follow another element add the class="trigger" to, this way it is re-useable. In the element you have added the class to, add a rel="#element-to-be-clicked" this will allow you to setup multiple clicks on different links.

    • So you are now capturing any clicks on an element with the class="trigger"
    • Finding the element you wanted to be clicked on rel="#element-to-be-clicked"
    • Getting the href address from the element
    • Changing the windows location to the new link

提交回复
热议问题