[javascript]把一個onchange事件event綁定在多個element,可避免程式碼重複

  • 1394
  • 0

[javascript]把一個onchange事件event綁定在多個element,可避免程式碼重複

實際例子來說,如果畫面上有兩個上傳檔案的元件,你就會很希望他們共用onchange事件了,不然程式碼就會重複很多喔

$(document).ready(function () {
	
	//設定file upload的 onchange event
	//addEventListener一定要搭配document.getElementById抓物件,用jquery $("#id")的方式抓物件不行
	document.getElementById("fileUpload1").addEventListener("change", function () {
		SetFileUploadOnChangeEvent(this.id, 'photo', 'AdImage', 'fileName', 905, 160);
	}, false);

	document.getElementById("fileUpload2").addEventListener("change", function () {
		SetFileUploadOnChangeEvent(this.id, 'photo02', 'AdImage02', 'fileName02', 445, 250);
	}, false);
});

function SetFileUploadOnChangeEvent(fileUploadId, imageHolderId, adImageId, labelfileNameId,
            Max_Width, Max_Height) 
{
	//do anything you want
}




參考資料:
How to pass parameter to function using in addEventListener?
https://stackoverflow.com/questions/12024483/how-to-pass-parameter-to-function-using-in-addeventlistener/12024498#12024498