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

function not being called, using jquery .delegate

本文关键字:使用 jquery delete 调用 函数      更新时间:2023-09-26

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

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

但我也希望能够在其他地方使用相同的功能。因此,与其多次编写相同的函数,我可以单独声明它,并按名称调用它,对吧?

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

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

在定义委托时删除括号。只需将函数名称命名为

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

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

最好这样做:

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

它的优点主要有:

  • 如果你想在活动结束后做其他事情,只需添加它
  • 您可以调用此表单中的更多函数(而不是单个alertMe()

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

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