Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need to have a way to call the closure that you have created to use it within the <code>onclick</code> attributes. The advantage of having <code>closure1</code> as a global variable is that the closure is created just once and you can re-use it throught the page by just calling <code>closure1(num, index)</code>. If however you don't like to have a variable named <code>closure1</code> in your global scope you could <em>clean up</em> in the following way.</p> <p><strong>EDIT :</strong> I had posted two suggested ways earlier. Thanks to @nnnnnn for pointing out that one of the ways would break the OP's code. I have removed the incorrect suggestion and left the correct suggestion as it is.</p> <p>You could add closures as properties to the existing <code>Closure</code> function. For example, if you want to create a new closure <code>closure1</code> you should create it like this</p> <p>Remove the line:</p> <pre><code>var closure1=Closure(0, 0); </code></pre> <p>add the following line <em>AFTER</em> the <code>Closure</code> function has been defined, like so:</p> <pre><code>Closure.closure1 = Closure(0, 0); </code></pre> <p>and replace your onclicks with</p> <pre><code>&lt;div id="d1" onclick="Closure.closure1(2,0)"&gt;2 index 0&lt;/div&gt; </code></pre> <p>The complete code would then look as follows:</p> <pre><code>&lt;script&gt; function Closure(num, i) { var num=num; var index=i; var anArray = []; return function(num,index) { anArray[index]=(num); out.innerHTML=anArray; } } Closure.closure1 = Closure(0, 0); &lt;/script&gt; &lt;div id="d1" onclick="Closure.closure1(2,0)"&gt;2 index 0&lt;/div&gt; &lt;div id="d2" onclick="Closure.closure1(5,3)"&gt;5 index 3&lt;/div&gt; &lt;div id="d3" onclick="Closure.closure1(4,1)"&gt;4 index 1&lt;/div&gt; &lt;div id="d4" onclick="Closure.closure1(9,7)"&gt;9 index 7&lt;/div&gt; &lt;div id="out" &gt;?&lt;/div&gt; </code></pre> <p>This is the cleanest approach in my opinion. Hope this helps.</p>
    singulars
    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