Note that there are some explanatory texts on larger screens.

plurals
  1. POGenerating a function from a string in Javascript
    text
    copied!<p>I am using jQuery to take data from an xml file and save it to a string. The string is a switch statement which I want to become a function.</p> <pre><code>$.get('type.xml', function(xml) { var cases=[]; $(xml).find('type').each(function(){ index=parseInt($(this).find('earn').text()); if($.isArray(cases[index])){ cases[index].push($(this).find('name').text()); }else{ arr=$.makeArray($(this).find('name').text()); cases[index]=arr; } }); var autoearn="function(x){switch(x){"; for(i=0;i&lt;=100;i+=5){ if($.isArray(cases[i])){ $.each(cases[i], function(index,v){ autoearn+='case "'+v+'":'; }); autoearn+='$("input[name^=\'earn\']").val('+i+');break;'; }} autoearn+='}}'; }); </code></pre> <p>The first section makes a 2D array that associates an array of cases to their resultant output by their index. So that something that earns $10 (e.g. Meeting) will be stored in cases[10] (Meeting=cases[10][0]).</p> <p>The second part writes a string that makes a puts into a switch statement that looks something like this:</p> <pre><code>function(x){ switch(x){ case "Meeting": $("input[name^='earn']").val(10); break; case "Event1": case "Event2": $("input[name^='earn']").val(20); break; } } </code></pre> <p>Note that the syntax for the switch cases make Event1 and Event2 have the same result.</p> <p>Now autoearn is just a string that has the code for the function I want. How do make into a function? Is there a better way to do this? I'm thinking of sending it through PHP to return it back to jQuery but this whole thing seems really indirect and there is probably an easier way to do this.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload