Basically, I have an autocomplete function to help users select an item. Whe开发者_如何学JAVAn they select an item, a series of variables relating to the item are saved. Once they click 'add', the variables are then injected into an HTML template, and the HTML template is injected into the DOM. My question is, how can I do this without having to mix my HTML code with the j/s code i.e. var example = "<div id='" + divId + "'></div>";
(etc.) I hope the question is clear enough.
Have you looked into jQuery Templates? It's basically client-side data binding, which seems like what you are trying to do.
For example, you can do stuff like this..
Assuming you have a list of Song objects, defined as:
var song = {
title : 'Purple Rain',
artist : 'Prince'
};
HTML:
<!-- Template definition -->
<script id="tmpl_songList" type="text/html">
<li>
<a>
<span>${title}</span>
<span>${artist}</span>
</a>
</li>
</script>
<!-- HTML container to host data-bound list -->
<ul id="song_list"></ul>
JS:
// bind data (songList) and append to HTML container.
$.tmpl($('#tmpl_songList'), songList).appendTo($('#song_list'));
You could do:
var example = $("<div />").attr("id",divId);
But when you have a lot of nested tags it can be tedious to create each element, in those cases i mix them up.
Try:
var myID = "id";
var myText = "Some Text"
$('<div/>', {
id: myID,
html: myText
}).appendTo('body');
You can add more properties, if needed.
On the other hand, if your manipulations are complex, use a template engine. It is easier to maintain.
精彩评论