Building UI dynamically with jQuery
Usually if I ever need to create new UI elements dynamically with jquery I just create a string of HTML and append that to an element using the .appendTo() method.
For example:
var i=0;
for (i=0;i<=5;i++)
{
$('<div id="box" + i><h1>Test</h1><p>This is a test</p></div>').appendTo('#Wrapper');
}
However, in this case I need to create a drop down select list as part of the UI that is bound to values provided by the server using the jquery ajax() method.
$('<div id="box" + i><h1>Test</h1><select>[The items must be created by an AJAX call to the server ]</se开发者_开发百科lect></div>').appendTo('#Box');
Is the best way to do this to call the ajax() method and create an array of items before parsing them to a string and then appending the string?
Or is there a more sophisticated way of doing this?
Here's an example from a project of mine. It should be pretty self explanatory but any questions you have are welcome.
var data;
var $cities = $("#cities");
$.ajax({
type: "POST",
url: "/umbraco/webservices/Helpers.asmx/getcities",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
data = jQuery.parseJSON(msg.d);
$cities.empty();
var $defaultOption = $("<option />").val("").text("Choose");
$cities.append($defaultOption);
$.each(data, function(key, value) {
var $city = $("<option />").val(key).text(key);
$cities.append($city);
});
}
});
I would usually create a select box with a given ID on the page, and then manipulate the elements of that select box by deleting all of the items in the list and replacing them with code like the following;
$("#selectBox option").remove();
$("#selectBox").append('<option value="1">Option 1</option>');
$("#selectBox").append('<option value="2">Option 2</option>');
To read more about the things you can do with a select box in jQuery, read here; http://hungred.com/how-to/tutorial-jquery-select-box-manipulation-plugin/
精彩评论