首页 > 解决方案 > 为什么我得到一个 SCRIPT5007: SCRIPT5007: Unable to set property 'disabled' of undefined or null reference in inter

问题描述

为什么在 Internet Explorer 中设置禁用属性不起作用?在 Internet Explorer 中,它会输出错误。在其他浏览器中它确实有效。错误发生在第 6 行和第 7 行。它输出的错误如下所示:

SCRIPT5007:SCRIPT5007:无法设置未定义或空引用的属性“禁用”。sql.html(6, 1)

这是我的代码

<html>
    <head>
        <script>
            if (!window.openDatabase){
                alert("Sorry your browser dosent support WebSQL")
                document.getElementById("input").disabled = true
                document.getElementById("button").disabled = true
            } else {
                var db = openDatabase("mydb", 1.0, "mydb", 2*1024*1024)
                function execute(){
                    db.transaction(function (t){
                        t.executeSql(document.getElementById("input").value)
                        console.log(document.getElementById("input").value)
                    })
                }
            }
        </script>
    </head>
    <body id="body">
        <textarea id="input"></textarea>
        <button onclick="execute()" id="button">Execute SQL</button>
    </body>
</html>

但是,在控制台的第 6 行和第 7 行键入代码确实有效。我的代码有什么问题?

标签: javascriptinternet-explorer

解决方案


页面从上到下加载,根据您的代码,当您使用getElementById方法获取textarea和button时,它们没有加载。因此,它找不到这些控件,并会显示“无法设置未定义或空引用的属性'禁用'”错误。

您可以将代码放在 onload 事件中。onload 事件在对象已加载时发生。

请修改您的代码如下:

<head>
    <script>
        function pageload() { 
            if (!window.openDatabase) {
                alert("Sorry your browser dosent support WebSQL")
                document.getElementById("input").disabled = true
                document.getElementById("button").disabled = true
            } else {
                var db = openDatabase("mydb", 1.0, "mydb", 2 * 1024 * 1024)
                function execute() {
                    db.transaction(function (t) {
                        t.executeSql(document.getElementById("input").value)
                        console.log(document.getElementById("input").value)
                    })
                }
            }
        }
    </script>
</head>
<body id="body" onload="pageload();">
    <textarea id="input"></textarea>
    <button onclick="execute()" id="button">Execute SQL</button>
</body>

推荐阅读