为什么jQuery会为元素的css函数返回undefined ?

Why would jQuery return undefined for the css function of an element?

本文关键字:函数 返回 undefined css jQuery 元素 为什么      更新时间:2023-09-26

jQuery 1.11.1,适用于Mac OS X Mavericks,最新版本的Safari。

我试图设置CSS属性与CSS函数。元素中缺少Css ()

首先,我验证了元素是否被正确选择:

// There is only one element that has id="container"
var $container = $('#container');
// Selector returns a collection. I have to access first element:
console.log($container[0]); // prints HTMLDivElement
// css function is undefined
console.log($container[0].css); // prints undefined
// Also can't set any css value. Gives undefined error.
$container[0].css({backgroundColor:'blue'});

错误是:

TypeError: 'undefined'不是一个函数美元的容器[0]. css({写成backgroundColor:"蓝"}))

我从测试页面中删除了所有内容。它包含jQuery,并且在主体中有一个带有ID的div。非常简单。下面是上面显示的JavaScript代码。

知道为什么div会缺少css功能吗?

这是因为你正在退出jQuery对象,并正在使用DOM元素…

$container[0].css({backgroundColor:'blue'});

这里的[0]从jQuery对象中获得DOM对象。

如果你想访问jQuery方法,请使用jQuery…

$container.css({backgroundColor:'blue'});

您正在错误地使用jQuery。当你说$container[0]你得到jQuery对象的第一个javascript DOM元素(它没有任何jQuery函数附加到它)。如果你想使用jQuery获得元素的css背景色,你需要做$container.css("background-color"),并设置它$container.css("background-color", "blue");$container.css({ "background-color": "blue" });

因为css函数是一个jquery对象的方法。当您执行$container[0]时,您将获得与选择器匹配的第一个DOM节点,该节点不是jquery对象。

试试$container.css(...)

当您访问集合项时,不再有jQuery方法,只有DOM元素。

你可以替换:

$container[0].css({backgroundColor:'blue'});

$container.css({backgroundColor:'blue'});

如果您有多个div元素具有相同的css属性,

例如,下面的语句返回多个结果:

var $container = $('.container');  // Has 3 results

如果你想达到特定元素的css属性,那么你可以将dom元素还原为jquery元素,并做你想做的,如下所示:

$($('.container').get(2)).css({ "background-color": "blue" });

http://jsfiddle.net/JNR63/

检查这个例子

alert($container.css("width"));