我有一個長期的上傳照片功能,使用隱藏的iFrames,它工作很好,一切都好,這是很多雜亂的代碼,我想使一個乾淨的函數,只有幾行或更少的代碼才能處理。需要簡化JavaScript功能(也使用jQuery)
function fileUpload(form, action_url)
{
// Create the iframe...
var iframe = document.createElement("iframe");
iframe.setAttribute("id","upload_iframe");
iframe.setAttribute("name","upload_iframe");
iframe.setAttribute("width","0");
iframe.setAttribute("height","0");
iframe.setAttribute("border","0");
iframe.setAttribute("style","width: 0; height: 0; border: none;");
// Add to document...
form.parentNode.appendChild(iframe);
window.frames['upload_iframe'].name="upload_iframe";
iframeId = document.getElementById("upload_iframe");
// Add event...
var eventHandler = function() {
if (iframeId.detachEvent)
iframeId.detachEvent("onload", eventHandler);
else
iframeId.removeEventListener("load", eventHandler, false);
// Message from server...
if (iframeId.contentDocument) {
content = iframeId.contentDocument.body.innerHTML;
} else if (iframeId.contentWindow) {
content = iframeId.contentWindow.document.body.innerHTML;
} else if (iframeId.document) {
content = iframeId.document.body.innerHTML;
}
if(content)
{
/* THIS CODE SHOULD BE DEFINED IN NEW FUNCTION, AND PLACED HER AUTOMATICALLY- onSuccess()
$('img.profile-picture').attr("src","photos/"+content+"_200.jpg");
$('.post-photo'+cookie('login')).attr("src","photos/"+content+"_55.jpg");
$(".add-photo-loading").fadeOut("fast");
*/
}
else
{
/*THIS SHOULD ALSO BE DEFINED IN THE NEW FUNCTION - onError()
$(".add-photo-loading").html("Invalid Filetype");
$(".add-photo-loading").attr("class","upload-error");
*/
}
// Del the iframe...
setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
}
if (iframeId.addEventListener)
iframeId.addEventListener("load", eventHandler, true);
if (iframeId.attachEvent)
iframeId.attachEvent("onload", eventHandler);
// Set properties of form...
form.setAttribute("target","upload_iframe");
form.setAttribute("action", action_url);
form.setAttribute("method","post");
form.setAttribute("enctype","multipart/form-data");
form.setAttribute("encoding","multipart/form-data");
// Submit the form...
form.submit();
/*THIS SHOULD BE FIRED IMMEDIATELY WHEN THIS FUNCTION IS CALLED BUT THIS CODE SHOULD ALSO BE FIRED ELSEWHERE
$(".upload-error").attr("class","add-photo-loading");
$(".add-photo-loading").html("Uploading...");
$(".add-photo-loading").css({"display":"block"});
*/
}
好了,所以有代碼在這裏的幾行應該在新的功能來定義,我有/ ** /代碼塊,與是該塊的動作周圍評論。
我刪除多餘的評論碼。然後,我將iframe/form參數移動到關聯數組,並通過遍歷該數組來設置iframe/form參數。 – Minras