Javascript - 用变量定义函数

时间:2013-03-31 15:58:25

标签: variables if-statement javascript

假设我有以下代码

var $variable = $('<li/>', { 
    tabindex: 0,
    click: function() {
        //more code in here
    }
}

是否可以使用变量定义click:?记住它已经在变量中,并且还包括if语句,如下所示:

if(condition) {
    var functiontype = 'click';
}
else {
    var functiontype = 'hover';
}
var $variable = $('<li/>', { 
    tabindex: 0,
    functiontype: function() {
        //more code in here
    }
}

我尝试过这样做,但它没有用。有人可以指出我正确的方向吗?

2 个答案:

答案 0 :(得分:2)

if(condition) {
    var functiontype = 'click';
}
else {
    var functiontype = 'hover';
}

var options = {};
options["tabindex"] = 0;
options[functiontype] = function(){
    // your code
}
var $variable = $('<li/>', options);

答案 1 :(得分:0)

你可以这样做:

var $variable = $('<li/>', { 
    tabindex: 0
};
$variable[condition?'click':'hover'] = function(){
   // the code here
}
相关问题