【问题标题】:JavaScript GetElementById is Null but Element Has a ValueJavaScript GetElementById 为 Null 但元素有值
【发布时间】:2019-02-03 14:29:43
【问题描述】:

我正在尝试将值从 JavaScript 传递到 HTML 以用于 Chrome 扩展。我不断收到一个错误,即被引用的元素为空。

popup.html

<!doctype html>
<html>
<head>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="popup.js"></script>
</head>
<body>
    <div>
        <h3>Output</h3>
        <br>
        <output id="outputKey">Output goes here</output>
    </div>
</body>
</html>

popup.js

chrome.storage.sync.get("key", function (value) {
    console.log("Output key value: " + value["key"]);
    console.log("Popup output key value: " + document.getElementById("outputKey"));
    //Set document.getElementById("outputKey") to value["key"]
  });

结果是它们从存储中检索到的键值是有效的,并且在使用console.log("Output key value: " + value["key"]); 时正确记录到控制台。我想将此值设置为output 元素的值,以便在popup.html 上显示它。我收到一条错误消息,提示 document.getElementById("outputKey") 为空。

我想知道这是否是因为仅当在浏览器中单击扩展按钮时才会显示扩展页面。我尝试添加以下内容,但没有成功。

popup.js

...
window.onload = function () {
    chrome.storage.sync.get("key", function (value) {
    console.log("New key value: " + value["key"]);
    document.getElementById("outputKey") = value["key"];
});

【问题讨论】:

    标签: javascript html dom google-chrome-extension google-chrome-app


    【解决方案1】:

    您的代码在 DOM 完全加载之前运行。在使用DOMContentLoaded 完全加载 DOM 之后,而不是 onload 执行您的代码。这将确保当您引用/使用该元素时该元素位于 DOM 中。

    请注意:您还必须使用textContentinnerTextvalue 等元素的属性来设置值。

    document.addEventListener("DOMContentLoaded", function(event) {
      chrome.storage.sync.get("key", function (value) {
        console.log("New key value: " + value["key"]);
        document.getElementById("outputKey").value = value["key"];
      }
    });
    

    【讨论】:

      【解决方案2】:

      使用下面的代码:

      document.getElementById("outputKey").value = value["key"];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-25
        • 1970-01-01
        • 1970-01-01
        • 2011-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-06
        相关资源
        最近更新 更多