简体   繁体   English

函数未被调用,使用jquery .delegate

[英]function not being called, using jquery .delegate

I want to use jquery delegate to call a function, and this works fine: 我想使用jquery委托来调用一个函数,这很好用:

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

But I also want to be able to use the same function elsewhere. 但我也希望能够在其他地方使用相同的功能。 So rather than writing the same function out several times, I can just declare it separately, and call it by name, right? 因此,不是多次编写相同的函数,我可以单独声明它,并按名称调用它,对吧?

But written this way, I never see the alert. 但是这样写,我从来没有看到警报。

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

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

Drop the parenthisis while defining delegate. 在定义委托时删除parenthisis。 just give the function-name 只需给出函数名称

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

jQuery .delegate has been superseded by the .on method. jQuery .delegate已被.on方法取代。 I would recommend you change your code to use it. 我建议你改变你的代码来使用它。

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

it's better to do this: 最好这样做:

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

it has advantages, mainly: 它有优势,主要是:

  • if you want other stuff done after the event, just add it in 如果您想在活动结束后完成其他活动,请将其添加进去
  • you can call more functions in this form (rather than that single alertMe() ) 你可以用这种形式调用更多的函数(而不是那个单一的alertMe()

Creating the common event handler is easy 创建公共事件处理程序很简单

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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