Variables Javascript-使用变量定义函数

Variables Javascript-使用变量定义函数,variables,if-statement,javascript,Variables,If Statement,Javascript,假设我有以下代码 var $variable = $('<li/>', { tabindex: 0, click: function() { //more code in here } } 我试过这样做,但没有成功。有人能给我指一下正确的方向吗?你可以倒过来: var $variable = $('<li/>', { tabindex: 0 }; $variable[condition?'click':'hover']

假设我有以下代码

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

我试过这样做,但没有成功。有人能给我指一下正确的方向吗?

你可以倒过来:

var $variable = $('<li/>', { 
    tabindex: 0
};
$variable[condition?'click':'hover'] = function(){
   // the code here
}
var$variable=$('
  • ',{ 索引:0 }; $variable[条件?'click':'hover']=函数(){ //这里的代码 }
  • 如果(条件){
    var functiontype='单击';
    }
    否则{
    var functiontype='hover';
    }
    var选项={};
    选项[“tabindex”]=0;
    选项[functiontype]=函数(){
    //你的代码
    }
    var$variable=$(“
  • ”,选项);
  • var $variable = $('<li/>', { 
        tabindex: 0
    };
    $variable[condition?'click':'hover'] = function(){
       // the code here
    }
    
    if(condition) {
        var functiontype = 'click';
    }
    else {
        var functiontype = 'hover';
    }
    
    var options = {};
    options["tabindex"] = 0;
    options[functiontype] = function(){
        // your code
    }
    var $variable = $('<li/>', options);