Note that there are some explanatory texts on larger screens.

plurals
  1. POConverting javascript string to code without using eval
    primarykey
    data
    text
    <p>I'm trying to do the below without using eval() as so many posts say it's slow and evil so you shouldn't use it as there's always alternative ways.</p> <p>The JS (note i'm using jquery)</p> <pre><code>$('a').click(function() { //Assign myVar to the id value of the a tag var myVar = $(this).attr('id'); $.getJSON("assets/js/json.js", function(json) { alert("json."+myVar+".thumb"); }); }); </code></pre> <p>And i have some basic html, which passing in the value for myVar</p> <pre><code>&lt;a id="imageID1" href="#"&gt;A link 1&lt;/a&gt;&lt;br /&gt; &lt;a id="imageID2" href="#"&gt;A link 2&lt;/a&gt; </code></pre> <p>Basic JSON file</p> <pre><code> { "imageID1" : { "thumb" : "assets/images/312px.png", "zoomThumb" : "assets/images/gallery/_AR_0063_m_thumb.jpg", "large" : "assets/images/gallery/_AR_0063.jpg" }, "imageID2" : { "thumb" : "another.png", "zoomThumb" : "assets/images/gallery/_anotherb.jpg", "large" : "assets/images/gallery/another.jpg" } } </code></pre> <p>So the ID for each link is passed to myVar on click, this is working fine but the alert value isn't correct.</p> <p>For example if imageID2 is click the alert should actually display "another.png" but instead it's displaying the code i actually want to run, "json.imageID@.thumb".</p> <p>Now i can change the alert line to</p> <pre><code> alert(eval("json."+myVar+".thumb")); </code></pre> <p>Which does the trick, but as mentioned don't want to use eval due to the know issues.</p> <p>So any alternative way of doing the above. Thanks in advance for any help or tips.</p> <p>Ben</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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