Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can shorten your code quite a bit like this:</p> <pre><code>var func1 = function() { alert("Function 1 is called");} var func2 = function() { alert("Function 2 is called");} // changed property name ----------v var myArray = [{id:"bt1", value:"+", click: func1}, {id:"bt2", value:"-", click: func2}]; $(function(){ $.each( myArray, function(i,v) { $('&lt;input&gt;',$.extend({},v,{type:"button"})).appendTo('#test'); }); }); </code></pre> <p><strong>Example:</strong> <a href="http://jsfiddle.net/yLPsK/" rel="nofollow">http://jsfiddle.net/yLPsK/</a></p> <p>I used the <a href="http://api.jquery.com/jQuery.each/" rel="nofollow"><code>jQuery.each()</code><sup><i>[docs]</i></sup></a> method to iterate your Array.</p> <p>Then I used the <a href="http://api.jquery.com/jQuery.extend/" rel="nofollow"><code>jQuery.extend()</code><sup><i>[docs]</i></sup></a> method to extend an empty object with the objects you created (changing <code>func</code> to <code>click</code>), as well as another one with the <code>type:"button"</code> info, and passed the result as the second argument to the <a href="http://api.jquery.com/jQuery/" rel="nofollow"><code>jQuery()</code><sup><i>[docs]</i></sup></a> method.</p> <p>If you add <code>type:"button"</code> to each object in your array, you can get rid of <code>$.extend</code>.</p> <pre><code>var func1 = function() { alert("Function 1 is called");} var func2 = function() { alert("Function 2 is called");} // changed property name ----------v var myArray = [{id:"bt1", value:"+", click: func1, type:"button"}, {id:"bt2", value:"-", click: func2, type:"button"}]; // added the "type" property -------------------^ $(function(){ $.each( myArray, function(i,v) { $('&lt;input&gt;', v).appendTo('#test'); }); }); </code></pre> <p><strong>Example:</strong> <a href="http://jsfiddle.net/yLPsK/1/" rel="nofollow">http://jsfiddle.net/yLPsK/1/</a></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.
    1. This table or related slice is empty.
    1. VO
      singulars
      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