为什么这会在 IE 11 中引发异常
Why does this throw an exception in IE 11
为什么在我单击按钮的 Internet Explorer 11 中,以下代码会抛出 'Unspecified error'(在 appendChild
行)?
<!DOCTYPE html>
<html>
<head>
<script>
function go() {
var popUp = window.open('about:blank');
popUp.document.body.appendChild(document.createElement('div'));
}
</script>
</head>
<body>
<button onclick="go()">Click Me</button>
</body>
</html>
您正在使用当前页面的文档创建 div,请尝试使用弹出窗口中的文档 window
popUp.document.body.appendChild(popUp.document.createElement('div'));
如果在处理用户事件(如点击)期间使用,弹出窗口阻止程序通常只允许 window.open
。如果您阻止了弹出窗口,这可能会导致问题。
您需要从用户发起的事件中调用 window.open,例如单击 link,然后 link 需要 target="_blank"
。否则,Chrome 和 Firefox 将阻止弹出窗口。
此外,由于在尝试将 div 附加到 popUp
之前未检查 popUp
是否存在 null
,因此触发了错误。如果没有弹出窗口,则不能向其附加元素。
(我忘记了这一点,Musa 让我记住了,所以谢谢)IE 将阻止附加在与元素附加到的 window 上下文不同的 window 上下文中创建的任何元素.因此,不是使用当前文档创建 DIV 节点,而是需要使用弹出窗口的上下文创建它。
总而言之,这就是代码的样子。
<!DOCTYPE html>
<html>
<head>
<script>
function go()
{
var popUp = window.open('about:blank');
try
{
// Make sure you have a body document when creating the new window....
popUp.document.write("<html><head><title></title></head><body></body>");
popUp.document.body.appendChild(popUp.document.createElement('div'));
}
catch(e)
{
console.log(e);
}
}
</script>
</head>
<body>
<button onclick="go()">Click Me</button>
</body>
</html>
为什么在我单击按钮的 Internet Explorer 11 中,以下代码会抛出 'Unspecified error'(在 appendChild
行)?
<!DOCTYPE html>
<html>
<head>
<script>
function go() {
var popUp = window.open('about:blank');
popUp.document.body.appendChild(document.createElement('div'));
}
</script>
</head>
<body>
<button onclick="go()">Click Me</button>
</body>
</html>
您正在使用当前页面的文档创建 div,请尝试使用弹出窗口中的文档 window
popUp.document.body.appendChild(popUp.document.createElement('div'));
如果在处理用户事件(如点击)期间使用,弹出窗口阻止程序通常只允许 window.open
。如果您阻止了弹出窗口,这可能会导致问题。
您需要从用户发起的事件中调用 window.open,例如单击 link,然后 link 需要 target="_blank"
。否则,Chrome 和 Firefox 将阻止弹出窗口。
此外,由于在尝试将 div 附加到 popUp
之前未检查 popUp
是否存在 null
,因此触发了错误。如果没有弹出窗口,则不能向其附加元素。
(我忘记了这一点,Musa 让我记住了,所以谢谢)IE 将阻止附加在与元素附加到的 window 上下文不同的 window 上下文中创建的任何元素.因此,不是使用当前文档创建 DIV 节点,而是需要使用弹出窗口的上下文创建它。
总而言之,这就是代码的样子。
<!DOCTYPE html>
<html>
<head>
<script>
function go()
{
var popUp = window.open('about:blank');
try
{
// Make sure you have a body document when creating the new window....
popUp.document.write("<html><head><title></title></head><body></body>");
popUp.document.body.appendChild(popUp.document.createElement('div'));
}
catch(e)
{
console.log(e);
}
}
</script>
</head>
<body>
<button onclick="go()">Click Me</button>
</body>
</html>