简体   繁体   English

document.getElementById在Mozilla中不起作用

[英]document.getElementById not working in Mozilla

I am having an issue with document.getElementByID in Mozilla. 我在Mozilla中遇到document.getElementByID的问题。 In the IE and Chrome my code is working well. 在IE和Chrome中,我的代码运行良好。

I have written the following code: 我写了以下代码:

<script type="text/javascript">
function test(x, y) {
var text1 = document.getElementById('text1');
 for (var i = 0; i < x.length; i++) {
    text1.innerText += x[i]; // prints 12345
  }
   text1.innerText += "\ny: " + y; // prints y: 1,2,3,4,5
  }
</script>


 <body>
<form id="form1" runat="server">
<div>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</div>
<div id="text1"></div>
</form>
</body>

Can any one tell why this doesn't work in FireFox? 谁能说出为什么在FireFox中不起作用?

I don't think it's the call to getElementById that's the problem — if it is, then you didn't give enough detail — but I can tell you that Firefox and some other browsers do not implement innerText . 我不认为这是对getElementById的调用(如果确实如此),那么您没有提供足够的详细信息–但我可以告诉您Firefox和其他一些浏览器未实现innerText For those browsers, you need to work with textContent or text nodes directly. 对于这些浏览器,您需要直接使用textContent或文本节点。

You can find out whether textContent is supported or not using feature detection: 您可以使用功能检测来确定是否支持textContent

var textContentOrInnerText = "textContent" in document.body 
                               ? "textContent" : "innerText";

Then, you use this variable for the property access in your code: 然后,将此变量用于代码中的属性访问:

text1[textContentOrInnerText] += x[i];

Feel free to shorten the variable to something you feel more comfortable with. 随意将变量缩短到您更喜欢的方式。 Note that there are some minor differences in behaviour between both properties, but mostly you won't notice them. 请注意,这两个属性之间在行为上有一些细微的差异,但是大多数情况下您不会注意到它们。

textContent is the standards behaviour which is why I test for that first in my code. textContent是标准行为,这就是为什么我在代码中首先对此进行测试的原因。

innerText is not referenced anywhere in the DOM standard, therefore it's non-standard and an IE only hack. innerText在DOM标准中的任何地方都没有引用,因此它是非标准的,并且是仅IE的一种方法。

Please use .textContent to get the text content. 请使用.textContent获取文本内容。

For browser support either use a library or a shim 对于浏览器支持,请使用库或填充程序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM