Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Create some template files with classes matching the object keys, and then cycle through the keys and populate the template file. For example:</p> <pre><code>function Album (album) { this.template = $('#template').clone().removeAttr('id'); this.album = album; } Album.prototype.html = function () { var i, val; for (i in this.album) { if (!this.album.hasOwnProperty(i)) { continue; } val = this.album[i]; this.template.find("." + i).html(val); } console.log(this.template); return this.template; } var foo = new Album({ title: 'Cheap Thrills', artist: 'Frank Zappa', genre: 'Rock and Roll' }); $('#main').html(foo.html()); </code></pre> <p>that's a <em>one-size-fits-all</em> attempt, though it won't really fit all needs. You can set conditions or what-have-you for cases where this solution doesn't fit your needs. For example, if the data is an image url, setting the innerHTML isn't very useful, so you would instead set the 'src' attribute, or create an img tag with an SRC attribute.</p> <p>A template file might look like this:</p> <pre><code>&lt;div class="album"&gt; &lt;div class="user"&gt;&lt;/div&gt; &lt;span class="foo"&gt;&lt;/span&gt; &lt;textarea class="bar"&gt;&lt;/textarea&gt; &lt;/div&gt; </code></pre> <p>Here's a quick fiddle: <a href="http://jsfiddle.net/bxw7Z/" rel="nofollow">http://jsfiddle.net/bxw7Z/</a></p> <p>If you don't like the idea of using classes, try <a href="http://ejohn.org/blog/html-5-data-attributes/" rel="nofollow">data-attributes</a> instead.</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