你不能用html()獲得它。我創建了一個函數,它接受一個序列化數組並填充一個容器以保存來自html的對話框。這是它是如何從對話框稱爲:
//Set current vals to html before saving
setInputVals('#' + $(this).attr('id'), $(this).find('input, select, textarea').serializeArray());
這是函數:
/*
* Sets input vals to a container
*
* @param container_id The id of the container
* @param inputVals The serialized array that will be used to set the values
*
* @return boolean. Modifies container
*/
function setInputVals(container_id, inputVals) {
//Order by name
var inputValsByName = new Array();
$.each(inputVals, function(key, value) {
inputValsByName[value.name] = value.value;
});
//Loop through inputs and set correct values
$.each($(container_id + " :input"), function(key, value) {
if (!value.name in inputValsByName) {
return true;
}
//Loop through each type. Make sure you add new types here when needed. Notice that val() won't work generally
//for changing the html, and that is why attributes were mostly used.
if (value.type == 'radio') {
//Remove checked attribute and add it to the correct one
$('input:radio[name=' + value.name + ']').removeAttr('checked');
$('input:radio[name=' + value.name + ']').filter('[value="' + inputValsByName[value.name] + '"]').attr('checked', 'checked');
} else if (value.type == 'checkbox') {
//Checked attribute for checkbox
if (inputValsByName[value.name] != undefined) {
$(this).attr('checked', 'checked');
} else {
$(this).removeAttr('checked');
}
} else if (value.type == 'textarea') {
//Set text to textarea
$(this).text(inputValsByName[value.name]);
} else if (value.type == 'select-one') {
//Remove selected attribue from the options and add the correct one.
$(this).find('option').removeAttr('selected');
$(this).find('option[value="' + inputValsByName[value.name] + '"]').attr('selected', 'selected');
} else if (value.type == 'text') {
//Set value attribute for text input
$(this).attr('value', inputValsByName[value.name]);
}
});
return true;
}
測試在主流瀏覽器。希望它能幫助別人! :)