當查找的元素具有style="display:none;"
時,我們有幾種情況$get('foo')
或document.getElementById('foo')
失敗。這似乎適用於某些瀏覽器,但不適用於其他瀏覽器;特別是下面顯示的情況在IE9兼容模式下正常工作,但在兼容模式關閉時失敗。getElementById()在顯示時無法獲取元素:無
任何人都可以解釋爲什麼會發生這種情況,以及我們如何解決它?一個例子如下。
我們的ASPX頁面包含
<span id="JobAddressCheckBoxWrapper" style="display: none;">
<asp:CheckBox ID="JobAddressCheckBox" CssClass="DefaultTextCell" runat="server" Text="__Job address"
Style="margin-right: 2em;" onclick="ShowJobAddress();" />
</span>
<span id="PredefinedReplyCheckBoxWrapper">
<asp:CheckBox ID="PredefinedReplyCheckBox" CssClass="DefaultTextCell" runat="server"
Text="__Pre-defined reply" onclick="ShowReplies()" AutoPostBack="false" Style="margin-right: 2em;" />
</span>
導致這個生成的HTML
<span style="display: none;" id="JobAddressCheckBoxWrapper">
<span style="margin-right: 2em;" class="DefaultTextCell">
<input id="JobAddressCheckBox" onclick="ShowJobAddress();" name="JobAddressCheckBox" type="checkbox">
<label for="JobAddressCheckBox">Job address</label>
</span>
</span>
<span id="PredefinedReplyCheckBoxWrapper">
<span style="margin-right: 2em;" class="DefaultTextCell">
<input id="PredefinedReplyCheckBox" onclick="ShowReplies();" name="PredefinedReplyCheckBox" type="checkbox">
<label for="PredefinedReplyCheckBox">Predefined reply</label>
</span>
</span>
下面的JavaScript語句應該導致包含對象包裝變量,但在某些瀏覽器,或在IE9兼容模式,jobAddressWrapper的值爲null。 predefinedReplyWrapper的值不會爲空。它們之間唯一的區別是JobAddressCheckboxWrapper有style="display:none;"
。
var jobAddressWrapper = $get('JobAddressCheckboxWrapper');
var predefinedReplyWrapper = $get('PredefinedReplyCheckBoxWrapper');
或
var jobAddressWrapper = document.getElementById('JobAddressCheckboxWrapper');
var jobAddressWrapper = document.getElementById('PredefinedReplyCheckBoxWrapper');
與由跨度包裹元件的HTML圖案是不相關的;還有其他情況下,元素不包含跨度,但如果它們具有style="display:none;"
,則仍然無法引用。
更新(在響應評論等):
- $獲取提供了一個快捷方式 Sys.UI.DomElement類的getElementById方法。 More info here
- 這些調用是在onload和 兩種函數中進行的,以響應用戶交互。無論哪種情況都會發生問題。
什麼是'$ get'?何時/如何執行js的這些行? – Bergi
史蒂夫,你說的聽起來真的很奇怪。 getElementById查找當前DOM樹中存在的任何內容,而不管設置了什麼顯示屬性。 – shabunc
也請編輯該問題以儘可能保持自身一致性,在這種情況下,僅僅爲解釋當前問題中使用的術語而提供另一個問題的鏈接並不是最佳解決方案。 – shabunc