简体   繁体   中英

event handler triggered before event occurs in jquery

I am doing a mega drop down menu whereby a user clicks on an item to display the extension. I want two results onclick of an item:

  1. the extension to be displayed
  2. the background color to change for the menu item(the one that is clicked)

but I am having a hard time and both of these results happen before the onclick event occurs.

All other things are so far good below is my code

//call the showMenu function to toggle menu items display   
showMenu("#market", "#marketDrop");
showMenu("#jobs", "#jobsDrop");
showMenu("#career", "#careerDrop");
showMenu("#tech", "#techDrop");
showMenu("#estate", "#estateDrop");
showMenu("#fair", "#fairDrop");
showMenu("#leisure", "#leisureDrop");
showMenu("#exclusive", "#exclusiveDrop");

//the showMenu function
function showMenu(listItem, dropDown){
  //first hide the main drop down containers
  $(dropDown).hide();   
  $(listItem).click(function() {
    $(dropDown).fadeToggle();
  });

  $(listItem).click().css("background-color", "#000");      
}

Your last line is triggering a click immediately, not binding a click handler.

Try this:

function showMenu(listItem, dropDown){
    //first hide the main drop down containers
    $(dropDown).hide();   

    // register the click handler
    $(listItem).click(function() {
        $(dropDown).fadeToggle();
        $(this).css("background-color", "#000");
    });
}

NB: modern jQuery uses .on('click', ...) rather than .click(...) . It helps avoid the confusion with .click being used to both trigger and bind handlers, depending on the argument list. I haven't modified your code to use that just in case you're still on an old version of jQuery.

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