我有几个与jQuery共享相同变量的click函数,所以我创建了一个返回这些变量的函数。
虽然这有效,但我想知道是否以编程方式说这是正确或最有效的方法:
function clickVars($me){
var $curStep = $('.cust-step-cur'),
$nextStep = $curStep.next('.cust-step'),
nextStepLen = $nextStep.length,
$list = $('.cust-list'),
$btnCheck = $('.cust-btn.checklist'),
hasChecklist = $me.hasClass('checklist');
return {
curStep: $curStep,
nextStep: $nextStep,
nextStepLen: nextStepLen,
list: $list,
btnCheck: $btnCheck,
hasChecklist: hasChecklist
};
}
// Checklist Click
$('.option-list a').on('click',function(){
var $me = $(this),
myVars = clickVars($me);
currentStepOut(myVars.curStep);
myVars.curStep.removeClass('cust-step-cur');
currentStepIn(myVars.nextStep, myVars.list, myVars.btnCheck);
});
// Navigation
$('.cust-btn').on('click',function(){
if(animReady === false)
return false;
var $me = $(this),
myVars = clickVars($me);
if(myVars.hasChecklist && myVars.list.hasClass('cust-step-cur'))
return false;
currentStepOut(myVars.curStep);
myVars.curStep.removeClass('cust-step-cur');
if(myVars.nextStepLen === 0 || $me.hasClass('checklist')) {
myVars.nextStep = myVars.list;
}
animReady = false;
currentStepIn(myVars.nextStep, myVars.list, myVars.btnCheck);
});
这是多个函数之间生成共享变量的标准方法吗?
答案 0 :(得分:2)
在AS3中,最好这样做:
// Variable definitions
var enabled:Boolean = false;
public function myFunction(){
enabled = true;
}
所以在JavaScript中我一直在做:
// Variable defintions
var a,b,c,d,e = 0;
function alterVariables(){
a = 1;
b = 2;
}
答案 1 :(得分:1)
您必须了解您不在功能之间共享变量。此外,每次单击这些元素时,即使您多次单击一个元素,也会一次又一次地调用clickVars函数。所以这段代码非常糟糕。检查一下:
// Defined ones
var nodes = {
$elements : $('.elements'),
$otherElements : $('.otherElements'),
}
// In case you have multiple .selector elements in your DOM
$('.selector').each(function() {
// Defined ones for each element
var $element = $(this), isList = $element.hasClass('.list');
$element.bind('click', function(){
nodes.$elements.addClass('clicked');
});
});
$('.anotherSelector').each(function() {
// Yep, here is some duplicate code. But there won't be any
// performance improvement if you create special method for
// such small piece of code
var $element = $(this), isList = $element.hasClass('.list');
$element.bind('click', function(){
nodes.$elements.addClass('clicked');
});
});