如何在jQuery中将变量用作事件名称?

时间:2013-03-17 15:28:10

标签: jquery

这可能是一个非常简单的修复。我似乎无法弄清楚这一点。

我已将事件名称存储在变量中,并希望在代码中使用它们,如下面的伪代码所示,但它似乎对我不起作用。请参阅以下代码中的注释。

var EVENT;
if (something == true) EVENT = "hover";
else EVENT = "click";

mynav = function() {
   $(".nav").not(".nav2").bind(EVENT, function() { // EVENT works fine here
   ......
   ......
   ......
   } (EVENT == "hover")?', function() {}':''; ); // If EVENT is "hover", I want to display function()... Not sure how to make it work here....
}

3 个答案:

答案 0 :(得分:0)

创建该函数,然后在任何您想要的地方调用它

function MyHover(){
alert('MyHover()');
} 

function MyClick(){
alert('MyClick()');
} 

var EVENT;
if (something == true) EVENT = "hover";
else EVENT = "click";

mynav = function() {
   $(".nav").not(".nav2").bind(EVENT, function() { // EVENT works fine here
   ......
   ......
   ......
   } (EVENT == "hover")? MyHover() : MyClick() ; ); // If EVENT is "hover", I want to display function()... Not sure how to make it work here....
}

答案 1 :(得分:0)

尝试将您的功能分开,如下所示:

function myHover () {}

function myClick() {}

并在您的代码中调用您的函数:

mynav = function() {
   $(".nav").not(".nav2").bind(EVENT, function() { // EVENT works fine here
   ......
   ......
   ......
   } , ((EVENT == "hover")?:myHover : myClick ));
}

答案 2 :(得分:0)

var EVENT = something == true ? "hover" : "click";
mynav = function() {
    $(".nav").not(".nav2").bind(EVENT, EVENT === "hover" ? function() {
        // Hover function
    } : function() {
        // Click function
    });
}