document.getElementById 在 iOS 模拟器上返回不存在的对象

document.getElementById returns non existing object on iOS simulator

本文关键字:返回 不存在 对象 模拟器 getElementById iOS document      更新时间:2023-09-26

我在HTML文件中添加了以下HTML和JavaScript代码,并将其加载到UIWebView中。点击"测试"按钮时,不会显示警报。实际上,HTML文档中没有id为"mydiv"的元素。代码有什么问题?或者我不能在UIWebView中使用 document.getElementById ?

<input type="button" value="Test" onclick="getElement()"/>
function getElement()
{
    var mydiv = document.getElementById("mydiv");
    if(typeof (mydiv) == 'undefined')
    {
        alert(typeof (mydiv));
    }
    mydiv = document.createElement("div");
    mydiv.style.width = 100+"px";
    mydiv.style.height = 200+"px";
    mydiv.id = "mydiv";
    document.body.appendChild(mydiv);
}

而不是检查未定义
将代码
更改为

 if(!mydiv)
    {
        alert(typeof (mydiv));
    }

如果存在
Mydiv dosent,这将发出警报JSFIDDLE 为你的代码