在jquery中发生事件之前触发的事件处理程序

时间:2012-10-30 15:48:32

标签: javascript jquery event-handling

我正在做一个大型下拉菜单,用户点击某个项目以显示扩展名。 我想要一个项目的两个结果:

  1. 要展示的扩展程序
  2. 要更改菜单项(单击的那个)的背景颜色
  3. 但是我很难在onclick事件发生之前发生这两个结果。

    以下所有其他内容都很好,我的代码

    //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");      
    }
    

1 个答案:

答案 0 :(得分:3)

您的最后一行是立即触发点击,而不是绑定点击处理程序。

试试这个:

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");
    });
}

注意:现代jQuery使用.on('click', ...)而不是.click(...)。它有助于避免混淆.click被用于触发和绑定处理程序,具体取决于参数列表。我还没有修改你的代码,以防万一你仍然使用旧版本的jQuery。