Denny Sutedja
Denny Sutedja

Reputation: 538

Execute String In Javascript Without Eval

I have done it with eval but I read that eval is evil. So I am curious: how do I write this without eval()?. I already tried some sample but it didn't work. Is it possible to do this without eval or is eval the only way?

$(".test").each(function(){
    var xyz = "";
    var w = $(this).last().attr("name");
    for(var i=0; i< (w-1);i++){
        var xyz = xyz + ".prev()";
    }
    var x = '$(this).first().parent()' + xyz;
    var y = x + '.find("td.one").attr("rowspan",'+w+');';
    eval(y);    
});

Upvotes: 0

Views: 499

Answers (1)

nnnnnn
nnnnnn

Reputation: 150040

eval() isn't evil, it's just almost always the wrong tool for the job. For example, your algorithm can be implemented without messing around with strings at all, so then you wouldn't need to consider eval():

$(".test").each(function(){
    var w = $(this).attr("name");
    var el = $(this).parent();
    for(var i=0; i < w-1; i++){
        el = el.prev();
    }
    el.find("td.one").attr("rowspan", w);
});

Note also that your use of .last() and .first() was redundant, because within your .each() loop this will refer to a single DOM node.

Upvotes: 2

Related Questions