简体   繁体   中英

jQuery click event when triggered programatically

I have a link with an inline onclick event:

<a href="#" onclick="somefunction();">click</a>

I registered an additional function on the onclick event:

jQuery("#addMoreOptions").live('click',function(){
        console.log('clicked');
    });

Which works fine when I click on the link on the browser, but not when I simulate programmatically:

jQuery("#addMoreOptions").click();

The programatical version triggers the inline event but not the "live" one.

When you have multiple functions attached to an event, what order does it use?

I am pretty sure this is caused by the order of things happening.

If you look at this live example you'll see everything works as expected. This is because the event is registered, and then called. The code looks like:

jQuery(document).ready(function(){   

    jQuery("#addMoreOptions").live('click',function(){
        console.log('clicked');
    });

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

});

function somefunction()
{
 alert("clicked");   
}

When the page loads, you get an alert and a console.log .

Now with the very small change of putting the $('#addMoreOptions').click(); before registering the event as in this live example you only get the alert from the inline function.

For reference the code is

jQuery(document).ready(function(){   
     $('#addMoreOptions').click();  

    jQuery("#addMoreOptions").live('click',function(){
        console.log('clicked');
    });   

});

function somefunction()
{
 alert("clicked");   
}

触发点击事件的另一种方法是使用.trigger()函数:

jQuery('#addMoreOptions').trigger('click');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM