TypeError: cannot read property 'css' of null

TypeError: cannot read property 'css' of null

我试图通过引用其 class 名称来设置我的 div 元素的最小高度,但返回时出现错误:TypeError: cannot read 属性 'css' 的 null.

HTML 元素:

<div class="container contentContainer" id="topContainer">
        <div class="row">
            <div class="col-md-6 col-md-offset-3" id="topRow">
                <p class="bold">Please scroll down for more information </p>
            </div>
        </div>
    </div>

Javascript:

<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>

<script>
    $(function () {
        var x = document.getElementsByClassName("contentContainer");
        alert(x);
        if(x != null)
        {
            $(".contentContainer").css('min-height',$(window).height());
        }
    });
</script>

关于我为什么会收到此错误的任何建议?请告诉我。

当我包含外部 javascript 文件时出现问题:

<!-- <script type="text/javascript" src="js/monthly.js"></script> -->

这是 jQuery 语法。

$(window).height();

您需要包含 jQuery 或使用本机 JavaScript 版本:

window.innerHeight;

要使用 jQuery,您需要包含 jQuery library

您在 JSFiddle 上遇到错误是因为您没有包含 jQuery。

Updated Fiddle

在左侧 nav-bar,有一个部分显示“Frameworks & Extensions”。你需要 select

jQuery (edge)

或该 drop-down 列表中的任何 jQuery 版本。

因为你没有包含 jQuery,$ 构造函数不存在,所以错误

TypeError: cannot read property 'css' of null.

被抛出是因为您试图访问 non-existent(空)对象的 属性。

您同时加载 jQuery 和 Bootstrap,它们都破坏了 $ 符号;仅使用 jQuery 您将使用规范名称:

jQuery(".contentContainer")
    .css('min-height', jQuery(window).height());

或者,使用包装器:

jQuery(function($) {
    $(".contentContainer").css('min-height',$(window).height());
});
var x = document.getElementsByClassName("contentContainer");

Returns 具有 class 的元素数组。像在普通数组中一样访问所需的元素。

x[0]     //The first element, if there is any.

如果您在浏览器控制台上输入 $ [ENTER],您会得到类似

的内容吗
function (a,b){return new e.fn.init(a,b,h)

如果选择器 $('.contentContainer') returns 为 null 而不是包含函数 css 的对象,则 $ 可能未引用 jQuery 或已在其中更改您包括 jquery.js 和您尝试 运行.

的代码

如果您在使用bootstrap-对话框时出现错误,请在bootstrap-dialog.js文件中注释掉以下代码行:

$backdrop.css('z-index', zIndexBackdrop + (dialogCount - 1) * 20);

这将停止 "TypeError: cannot read property 'css' of null" 错误。

如果你的错误不是在使用bootstrap对话框时发生的,打开相关的js文件,然后注释掉里面所有的css文件引用,然后重新运行 网页。它应该 运行 成功。然后逐行取消注释代码并重新测试页面,直到它再次中断。这最终会把你带到恶棍代码行,然后你可以把它注释掉,避免这个错误继续发生。