【问题标题】:javascript and jsquery working only from consolejavascript 和 jsquery 只能从控制台工作
【发布时间】:2020-04-25 05:52:21
【问题描述】:

当我使用此代码 resize() 进入控制台时没有错误,并且框将其高度调整为宽度。

function resize() {
    let box = document.getElementById("id");
    let width = $("#id").width();
    box.style.height = width;
}

我想自动执行此操作,所以我只是尝试在 js 文件的末尾添加 resize();,如下所示:

function resize() {
    let box = document.getElementById("id");
    let width = $("#id").width();
    box.style.height = width;
}

resize();

但是什么也没发生,并且控制台出现错误:

Uncaught TypeError: Cannot read property 'style' of null
    at resize (main.js:4)
    at main.js:7
resize @ main.js:4
(anonymous) @ main.js:7

【问题讨论】:

  • 也许 JavaScript 在 DOM is ready 之前执行。
  • 尝试将函数调用包装到 10 秒的 setInterval 中,即使在 10 秒之前控制台中也出现了同样的错误。
  • 有关更多信息,在控制台中执行 resize() 效果很好,但也会打印 undefined

标签: javascript jquery css console


【解决方案1】:

您必须将您的函数调用封装在一个就绪函数中,因为元素可能尚未加载。

$(function() {
    resize();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多