简体   繁体   中英

Jquery click in on click handler

I have some strange behaviour with the jquery click event. This was my code:

$("#item").on("click",function(){
    //do some stuff
    $("#item2").click(); // doesn't work!
});

But the second click is not working when clicking #item. When manually clicking item2 it does work. I got it to work when doing this:

$("#item").on("click",function(){
    //do some stuff
    document.getElementById("item2").click(); //WORKS!
});

I also tried event.preventDefault() before the jquery click trigger but that doesn't work either.

Can somebody explain why this doesn't work with jquery?

You cant use click() as a simple method, it must be a function, so you should trigger() the click event:

$("#item").on("click",function(){
    //do some stuff
    $("#item2").trigger("click");
});

 $(function(){ $("#item").on("click",function(){ //do some stuff $("#item2").trigger('click'); // Now Works !!! }); $("#item2").on("click",function(){ //do some stuff alert('working') }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="item">item1</button><button id="item2">item1</button> 

please see this fiddle . I have added

$("#item2").trigger('click'); 

in your code.

Here is your solution:

$("#item2").trigger('click'); // use trigger function of jQuery

Have you read the documentation of JQuery? in https://api.jquery.com/click/ there explained aout onClick, and you can find why event.preventDefault doesn't work before the JQuery Trigger

For Solution :

$("#item2").trigger('click'); // Use trigger function of jQuery to Trigger

Please Read the Documentation

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