0

我有一个 uidialog 并希望获得它的全部内容,但是由于某种原因,如果我使用 .html(),我会获得旧的 HTML 内容,但如果我使用序列化,我会获得当前的实时内容。

所以,在我的对话框中,我有:

alert($(this).find('form').serialize()); //This serializes current live contents, as they appear in the uidialog form.
alert($(this).html()); //This shows the html before any modifications on the dialog

为什么 html() 显示修改前的 html,而 serialize() 显示输入的当前值的序列化?

4

1 回答 1

1

您无法使用 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;
} 

在主流浏览器上测试。希望它可以帮助某人!:)

于 2013-07-31T10:02:19.493 回答