直接呼叫 window.location.reload() 時,若頁面上有表單提交過資料,瀏覽器會跳出「是否重新提交表單」的確認框,打斷使用者操作。本文先給出解法,再順手整理一批 IE 與 Firefox 的相容性差異。
關鍵技巧是先改寫 href,再呼叫 reload:
window.location.href = window.location.href;
window.location.reload();
刷新父視窗同理:
window.opener.location.href = window.opener.location.href;
window.opener.location.reload();
原理在於重新賦值 href 會重置頁面的提交狀態,此後的 reload 不再被視為「重送表單」。
<iframe src="1.htm" name="ifrmname" id="ifrmid"></iframe>
方案一:以 name 定位
<input type="button" value="Button"
onclick="document.frames('ifrmname').location.reload()">
<input type="button" value="Button"
onclick="document.all.ifrmname.document.location.reload()">
方案二:以 id 定位
<input type="button" value="Button"
onclick="document.getElementById('ifrmid').contentWindow.location.reload()">
方案三:跨來源時
基於同源政策,無法直接操作外站 iframe 的內容,只能重新載入:
<input type="button" value="Button"
onclick="window.open(document.getElementById('ifrmid').src, 'ifrmname')">
以下以 IE 代指 Internet Explorer、MF 代指 Mozilla Firefox。
IE 可用 document.formName.item("itemName"),MF 不支援。改用 document.formName.elements["elementName"]。
IE 接受 (),MF 只接受 []:
document.forms("formName") → document.forms["formName"]
document.getElementsByName("inputName")(1)
→ document.getElementsByName("inputName")[1]
MF 沒有全域 event 物件,事件物件只能透過事件處理函式的參數取得。相容寫法:
<input type="button" name="someButton" value="提交" onclick="gotoSubmit(event)">
<script>
function gotoSubmit(evt) {
evt = evt ? evt : (window.event ? window.event : null);
alert(evt);
}
</script>
若堅持不改呼叫端(不傳參數),程式仍可在 IE 下運行,只是 MF 取不到事件物件。
IE 允許直接用 HTML 元素的 id 當變數使用,MF 不行。統一改用 document.getElementById("idName")。
IE 可用 eval(idName) 取得元素,MF 不可。改用 document.getElementById(idName)。
宣告變數時一律加上 var 可避免歧義;同時盡量不要讓變數名與元素 id 同名。
MF 沒有 x、y 屬性,等效的是 pageX。IE 則支援 clientX,因此可用 clientX 作為共同交集;若要求完全一致,可寫成:
mX = event.x ? event.x : event.pageX;
<frame src="xx.htm" id="frameId" name="frameName" />
IE 可用 id 或 name 訪問對應的 window 物件,MF 只能用 name:
IE:window.top.frameId 或 window.top.frameName
MF:window.top.frameName
兩者都支援 window.top.document.getElementById("frameId"),也都能用 window.top.frameName.location = 'xx.htm' 切換內容。
MF 中自訂屬性必須透過 getAttribute() 讀取。
MF 沒有 parentElement、children,需改用 parentNode、parentNode.childNodes。此外 MF 遵循 DOM 規範,childNodes 會把空白納入為文本節點,導致索引錯位,實務上建議改用 getElementsByTagName 這類查詢方法迴避。
當 HTML 結構不嚴謹時,兩者對 parentNode 的解讀也不同:
<form>
<table><input/></table>
</form>
MF 中 input.parentNode 是 form,IE 中則可能回傳空節點。MF 也沒有 removeNode 方法,需寫成 node.parentNode.removeChild(node)。
舊版 IE 不支援 const,請以 var 代替。
MF 的 body 在標籤尚未被完整解析前就存在,IE 則需等 body 完全讀入。
在 JavaScript 字串中就直接寫 &,不要寫 &,否則參數可能無法正確傳到伺服器;但在 XML 格式的模板檔中則必須跳脫。
MF 中所有節點都有 nodeName,但文本節點沒有 tagName。使用 tagName 時應先判斷是否為空。
IE 下 input.type 為唯讀,MF 下可以修改。
IE 中 getElementsByName() 與 document.all[name] 都無法取得 div 元素。
下列標註「IE 通用」者為建議採用的相容寫法,未標註者在 IE 中無效:
驗證是否為 IE:
var agt = navigator.userAgent.toLowerCase();
var is_ie = (agt.indexOf("msie") != -1) && document.all;
事件委派上的差異:IE 寫成 document.body.onload = inject;,而 MF 需寫成 document.body.onload = inject(); 或 new Function('inject()')。
MF 無法取得 event.srcElement,可改用 attr 綁定參數:
if (isIE) {
thistable.attachEvent("onmousedown", OnClickChangeTdBackColor);
} else {
for (var i = 0; i < thistable.rows.length; i++) {
var rowObj = thistable.rows[i];
for (var j = 0; j < rowObj.cells.length; j++) {
rowObj.cells[j].setAttribute("onmousedown",
"OnClickChangeTdBackColor(this)");
}
}
}
通用的事件處理函式寫法:
btn.onclick = handle_btn_click;
function handle_btn_click(evt) {
if (evt == null) evt = window.event; // IE
// 處理事件
}
若函式與事件沒有直接掛鉤,需要把 event 一路傳遞,可透過 caller 與 arguments 向上搜尋:
function SearchEvent() {
if (document.all) return window.event; // IE
var func = SearchEvent.caller;
while (func != null) {
var arg0 = func.arguments[0];
if (arg0 && arg0.constructor === Event) return arg0;
func = func.caller;
}
return null;
}
再搭配 __defineGetter__,就能在 Firefox 中補出 window.event 與 event.srcElement:
if (window.addEventListener) {
FixPrototypeForGecko();
}
function FixPrototypeForGecko() {
HTMLElement.prototype.__defineGetter__("runtimeStyle", function () {
return this.style;
});
window.constructor.prototype.__defineGetter__("event", function () {
return SearchEvent();
});
Event.prototype.__defineGetter__("srcElement", function () {
return this.target;
});
}
父元素:IE 用 obj.parentElement,MF 用 obj.parentNode;由於兩者都支援 DOM,優先選 parentNode。
ASP.NET 的 UniqueID 與 ClientID:使用 getElementById 時,應傳入控件的 ClientID。
操作 select 選項:移除項目,IE 可用 sel.options.remove(sel.selectedIndex);新增項目建議統一用標準 DOM:
var opnObj = document.createElement("OPTION");
opnObj.value = value;
opnObj.text = text;
subCatalog.appendChild(opnObj);
至於 cursor:hand 與 cursor:pointer,前者為 IE 專屬,建議統一寫 pointer。
這些差異在今天多已成為歷史,但理解它們有助於維護老系統,也更能體會「遵循標準、避免瀏覽器嗅探」這條原則的由來。