2013-07-25 103 views
0

我有一個uidialog,並希望獲得它的全部內容,但是由於某種原因,如果我使用.html()獲取舊的HTML內容,但是如果使用序列化,則獲取當前的實況內容。獲取uidialog全部內容

所以,我的對話框裏面,我有:

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,而序列化()顯示我與當前值的序列作爲輸入?

回答

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; 
} 

測試在主流瀏覽器。希望它能幫助別人! :)