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

iam*_*mer 3 javascript jquery

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'});
Run Code Online (Sandbox Code Playgroud)

错误是:

TypeError:'undefined'不是函数(评估'$ container [0] .css({backgroundColor:'blue'})')

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

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

Fen*_*ton 6

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

$container[0].css({backgroundColor:'blue'});
Run Code Online (Sandbox Code Playgroud)

[0]这里让你从jQuery对象的DOM对象.

如果要访问jQuery方法,请使用jQuery ...

$container.css({backgroundColor:'blue'});
Run Code Online (Sandbox Code Playgroud)