Denny Sutedja Denny Sutedja - 1 year ago 100
jQuery Question

Execute String In Javascript Without Eval

I have done it with

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

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("").attr("rowspan",'+w+');';

Answer Source

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():

    var w = $(this).attr("name");
    var el = $(this).parent();
    for(var i=0; i < w-1; i++){
        el = el.prev();
    el.find("").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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download