我们在 IE11/Chrome 上遇到了一个奇怪的问题。我们有这个小代码:
divFrmPost = document.getElementById('divFormPost');
divFrmPost.innerHTML = '<form name="formPost" method="post" \ action="http://someurl/servlet/myapp"> \
<input type="hidden" id="cd_user" name="cd_user" value="John Doe"> \
<input type="hidden" id="cod_user" name="cod_user" value="5013"> \
<input type="hidden" id="login" name="login" value="jdoe"> \
<input type="hidden" id="pwd" name="pwd" value="123456"> \
<input type="hidden" id="profile" name="profile" value="12"> \
<input type="hidden" id="" name="" value="128"> \
</form>';
frmPost = document.getElementById('formPost');
frmPost.submit();
当我们在 IE11 中运行它时,表单处理正常,但是当我们在 Chrome (v44) 中运行它时,它什么也不做,并且在控制台中出现以下错误:
未捕获的类型错误:无法读取 null 的属性“提交”
我们知道问题一定是最后一个隐藏字段,没有 id/name,但为什么它在 IE11 中工作而在 Chrome 中不起作用?
编辑:在原始代码中,innerHTML 构造是一行,我对其进行了编辑以便更好地阅读,但我忘记添加反斜杠。
EDIT2:请避免评论战...
最佳答案
让它发挥作用
首先我们必须编辑代码以使其正常工作: 正如其他人所说,您正在寻找 id,但在表单上只有名称集,而 Chrome 和其他真正的浏览器不喜欢它。
divFrmPost = document.getElementById('divFormPost');
divFrmPost.innerHTML = '<form id="formPost" method="post" action="http://someurl/servlet/myapp">'
+ '<input type="hidden" id="cd_user" name="cd_user" value="John Doe">'
+ '<input type="hidden" id="cod_user" name="cod_user" value="5013">'
+ '<input type="hidden" id="login" name="login" value="jdoe">'
+ '<input type="hidden" id="pwd" name="pwd" value="123456">'
+ '<input type="hidden" id="profile" name="profile" value="12">'
+ '<input type="hidden" id="" name="" value="128">'
+'</form>';
frmPost = document.getElementById('formPost');
frmPost.submit();
<div id="divFormPost"></div>
多行字符串
要在多行上连接字符串,您应该使用 +
为什么它可以在 IE 上运行?
答案在这里
getElementById method < IE 8
Returns a reference to the first object with the specified value of the ID or NAME attribute.
来自MSDN Microsoft getElementById method
也许它在 IE 11 上适合你,因为 this ,如果你不定义 <!DOCTYPE>
IE 会启用 Quirks 模式
Quirks mode emphasizes compatibility over standards compliance by supporting behavior found in earlier versions of Internet Explorer.
关于Javascript 代码可以在 IE11 中运行,但不能在 Chrome 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33891449/