【发布时间】:2012-08-18 17:27:01
【问题描述】:
当正在查找的元素具有style="display:none;" 时,我们有几个$get('foo') 或document.getElementById('foo') 失败的案例。这似乎在某些浏览器中有效,但在其他浏览器中无效;特别是下面显示的情况在具有兼容模式的 IE9 中可以正常工作,但在关闭兼容模式时会失败。
谁能解释为什么会发生这种情况,以及我们如何解决它?下面是一个例子。
我们的 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。预定义ReplyWrapper 的值永远不会为空。它们之间的唯一区别是 JobAddressCheckboxWrapper 有style="display:none;"。
var jobAddressWrapper = $get('JobAddressCheckboxWrapper');
var predefinedReplyWrapper = $get('PredefinedReplyCheckBoxWrapper');
或
var jobAddressWrapper = document.getElementById('JobAddressCheckboxWrapper');
var jobAddressWrapper = document.getElementById('PredefinedReplyCheckBoxWrapper');
元素被 span 包裹的 HTML 模式是不相关的;还有其他一些情况,元素没有被 span 包裹,但如果它们有 style="display:none;",仍然不能被引用。
更新(响应 cmets 等):
- $get 提供了一个快捷方式到 getElementById 方法的 Sys.UI.DomElement 类。 More info here
- 这些调用是在从 onload 和 响应用户交互。两种情况都会出现问题。
【问题讨论】:
-
什么是
$get?这些 js 行何时/如何执行? -
史蒂夫,你说的话听起来真的,真的很奇怪。 getElementById 发现当前 DOM 树中存在任何内容,无论设置了什么显示属性。
-
另外,请编辑问题以使其尽可能自洽,在这种情况下,提供指向另一个问题的链接只是为了解释当前问题。
-
document.getElementById()在我在这里尝试的所有 IE 版本中的隐藏 HTML 上似乎都可以正常工作:jsfiddle.net/jfriend00/dtEGR。一定还有其他问题让您感到困惑,因为我认为document.getElementById()没有问题。