javascript document.getElementbyId 在 IE 11 中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27704965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:51:57  来源:igfitidea点击:

document.getElementbyId is not working in IE 11

javascripthtmldominternet-explorer-11

提问by Vignesh

Am trying to fetch the entire div content and displaying in a alert message using document.getElementById. It is working fine in IE 8 & 9, but not in IE 10 & 11.

我正在尝试使用 document.getElementById 获取整个 div 内容并显示在警报消息中。它在 IE 8 和 9 中工作正常,但在 IE 10 和 11 中却没有。

Below is the code snippet which am using.

下面是正在使用的代码片段。

<body>
  <div id="oDiv1"><input type="text" ></div>
  <div id="oDiv2">Div #2</div>
  <div id="oDiv3">Div #3</div>
  <input type="button" value="Show First DIV Content" onclick="fnGetId()">
</body>

Javascript code

Javascript代码

<script type="text/javascript">
     function fnGetId() {
             var oVDiv=document.getElementById("oDiv1").innerHTML;
             alert(oVDiv);    
    }
</script>

Am entering some text in that textbox. In IE 8 & 9 its taking the oDiv1 content along with the text which I entered. Like below

我正在该文本框中输入一些文本。在 IE 8 和 9 中,它采用 oDiv1 内容以及我输入的文本。像下面

<input type="text" value="aaa">

But in IE 10 & 11, its taking the input tag but not the value which I entered.

但是在 IE 10 和 11 中,它采用输入标签而不是我输入的值。

<input type="text" value="">

Where am I going wrong? How can I get the content along with the values which I entered in IE11?

我哪里错了?如何获取内容以及我在 IE11 中输入的值?

回答by Ryan

Because you are not getting the right value and you are not getting the right element. Here is a hacky solution.

因为您没有获得正确的价值,也没有获得正确的元素。这是一个hacky解决方案。

var oVDiv=document.getElementById("oDiv1").children[0].value;

A better pattern would be to create a real form, and serialize the form values on submit.

更好的模式是创建一个真正的表单,并在submit上序列化表单值。

JSfiddle example

JSfiddle 示例