简体   繁体   English

Javascript - 用变量定义函数

[英]Javascript - define function with variable

Let's say I have the following code 假设我有以下代码

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

is it possible to define the click: with a variable? 是否可以定义click:使用变量? Baring in mind it is already inside a variable and will also include an if statement, like so: 记住它已经在变量中,并且还将包含if语句,如下所示:

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

I tried doing this but it didn't work. 我试过这样做,但它没有用。 Can someone please point me in the right direction? 有人可以指点我正确的方向吗?

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

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

You may do the reverse : 你可以反过来:

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

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

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