1

我有几个带有 jQ​​uery 的 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);
});

这是在多个函数之间生成共享变量的标准方式吗?

4

2 回答 2

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;
 }
于 2012-08-25T18:29:31.797 回答
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');
   });
});
于 2012-08-26T01:51:23.560 回答