开发者

Help on eval() function

开发者 https://www.devze.com 2023-04-03 09:22 出处:网络
I need help on this eval() problem: var ScoreFuncName = \'scoreCondition_\' + criteriaName; var allCheckBox = $(\'div#\'+SubListId).find(\"input:image[name^=\'\" + ChkBoxPrefix + \"\'][value=\'1\']\

I need help on this eval() problem:

var ScoreFuncName = 'scoreCondition_' + criteriaName;

var allCheckBox = $('div#'+SubListId).find("input:image[name^='" + ChkBoxPrefix + "'][value='1']");

eval(ScoreFuncName + '(' + allCheckBox.length + ')');

The eval() function is evaluating which checkbox is ticked and will do other things accordingly, it work开发者_开发问答ed great in Firefox but not in google Chrome and IE.

Scratching my head for 3 days on how to fix this. Thank you.


You should not be using eval for that.

If the function is in global scope. All you need to do is

window[ScoreFuncName](allCheckBox.length);

It would be better to name space it instead of using a global with window


Eval is not needed to do this. Also take notice that I am calling size on the jQuery object rather than length.

var scoreFunc = this['scoreCondition_' + criteriaName];

var allCheckBox = 
    $('div#'+SubListId).find("input:image[name^='" + ChkBoxPrefix + "'][value='1']");

scoreFunc(allCheckBox.size()); 


Hm... don't.

There realistically is not a need to use eval in this condition (and I would say that there is no need for a string look-up of the function). Since it looks clear that you have a finite and knowable number of conditions and a finite and knowable number of functions, then you can simply use a switch to actually select a function dynamically:

var toRun; // variable to store the function.
switch(criteriaName)
{
    case "criteria1":
       // keep the actual function in the variable, not some string.
       toRun = function(e){console.log("I is so special! " + e)}
       break;
    case "criteria2":
       toRun = function(e){console.log( e + " is not a squid!" )}     
       break;
}
var allCheckBox = $('div#'+SubListId).find("input:image[name^='" + 
                     ChkBoxPrefix + "'][value='1']"); 
// then just call it!
toRun(allCheckBox.length)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号