TypeError:无法读取null的属性’css’
我试图通过引用它的类名来设置我的div元素的最小高度,但它返回错误: TypeError:无法读取null的属性’css’ 。
HTML元素 :
Please scroll down for more information
Javascript :
$(function () { var x = document.getElementsByClassName("contentContainer"); alert(x); if(x != null) { $(".contentContainer").css('min-height',$(window).height()); } });
有关为什么我收到此错误的任何建议? 请告诉我。
当我包含我的外部JavaScript文件时,会出现问题:
<!-- -->
你正在同时加载jQuery和Bootstrap,它们都破坏了$
符号; 要仅使用jQuery,您将使用规范名称:
jQuery(".contentContainer") .css('min-height', jQuery(window).height());
或者,使用包装器:
jQuery(function($) { $(".contentContainer").css('min-height',$(window).height()); });
这是jQuery语法。
$(window).height();
您需要包含jQuery或使用本机JavaScript版本:
window.innerHeight;
为了使用jQuery,您需要包含jQuery库
您在JSFiddle上收到错误,因为您没有包含jQuery。
更新小提琴
在左侧导航栏上,有一个部分显示“ 框架和扩展 ”。 你需要选择
jQuery (edge)
或者从该下拉列表中的任何jQuery版本。
因为你没有包含jQuery, $
构造函数不存在,所以错误
TypeError: cannot read property 'css' of null.
因为您尝试访问不存在的(null)对象的属性而被抛出。
var x = document.getElementsByClassName("contentContainer");
返回具有该类的元素数组。 像在普通数组中一样访问所需元素。
x[0] //The first element, if there is any.
如果您在浏览器控制台上键入$ [ENTER],您会得到类似的结果
function (a,b){return new e.fn.init(a,b,h)
如果选择器$(’。contentContainer’)返回null而不是包含函数css的对象,则可能$不引用jQuery,或者在包含jquery.js和您尝试运行的代码的位置之间进行了更改。
如果在使用bootstrap-dialog时发生错误,请在bootstrap-dialog.js文件中注释掉以下代码行:
$ backdrop.css(’z-index’,zIndexBackdrop +(dialogCount – 1)* 20);
这会停止“TypeError:无法读取属性’css’of null”错误。
如果在使用bootstrap-dialog时没有发生错误,请打开相关的js文件,然后注释掉其中的所有css文件引用并重新运行该网页。 它应该成功运行。 然后逐个取消注释代码行并重新测试页面,直到它再次中断。 这最终将引导您进入恶棍代码行,然后您可以将其注释掉并避免此错误。