【问题标题】:function not being called, using jquery .delegate函数没有被调用,使用 jquery .delegate
【发布时间】:2012-03-24 07:22:49
【问题描述】:

我想使用 jquery 委托来调用一个函数,这很好用:

$("body").delegate("div", "mouseover", function(){
alert("it works");
});

但我也希望能够在其他地方使用相同的功能。所以与其把同一个函数写好几次,我可以单独声明它,并通过名字来调用它,对吧?

但是这样写,我从来没有看到警报。

function alertMe(){
alert("it works");
};

$("body").delegate("div", "mouseover", alertMe());

【问题讨论】:

    标签: javascript jquery function delegates declaration


    【解决方案1】:

    在定义委托时去掉括号。只需给出函数名称

    $("body").delegate("div", "mouseover", alertMe);
    

    【讨论】:

    • 这对我有用。谢谢老哥!
    【解决方案2】:

    jQuery .delegate 已被 .on 方法取代。我建议您更改代码以使用它。

    function alertMe(){
        alert("it works");
    }
    
    $("body").on("mouseover", "div", alertMe);
    //$("body").delegate("div", "mouseover", alertMe) -- old method
    //Note the change in postion of selector and event
    

    【讨论】:

      【解决方案3】:

      最好这样做:

      $("body").delegate("div", "mouseover", function(){
         alertMe();
         //plug more code down here
      });
      

      它有优点,主要是:

      • 如果您想在活动结束后完成其他工作,只需添加即可
      • 您可以以这种形式调用更多函数(而不是单个alertMe()

      【讨论】:

      • @dku.rajkumar 你碰巧读过他的帖子吗?他想在任何地方打电话给alertMe(),而不仅仅是alert()。我的答案在回调函数中调用alertMe(),这样,您可以调用更多的函数,而不仅仅是alertMe()
      【解决方案4】:

      创建通用事件处理程序很容易

      function alertMe(event){
          //you also need to include the event object, for various actions like stopPropagation()
          alert("it works");
      };
      
      $("body").delegate("div", "mouseover", alertMe);
      

      【讨论】:

        猜你喜欢
        • 2017-07-26
        • 1970-01-01
        • 2013-11-26
        • 1970-01-01
        • 2013-01-19
        • 1970-01-01
        • 2011-11-15
        • 2013-10-21
        • 1970-01-01
        相关资源
        最近更新 更多