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'不是一个函数(正在评估'$ container [0] .css({backgroundColor:'blue'})')
我从测试页中删除了所有内容。它包括jQuery,并且在主体内具有带有ID的div。很简单的。在此之下,上面显示了JavaScript代码。
任何想法,为什么div将缺少css函数?
您使用的jQuery错误。当您说$container[0]
时,您将获得jQuery对象的第一个javascript DOM元素(该对象未附加任何jquery函数)。如果要使用jQuery获取元素的CSS背景颜色,则需要执行$container.css("background-color")
,并将其设置为$container.css("background-color", "blue");
或$container.css({ "background-color": "blue" });
这是因为您退出了jQuery对象,并且正在使用DOM元素...
$container[0].css({backgroundColor:'blue'});
[0]
在这里从jQuery对象获取DOM对象。
如果要访问jQuery方法,请使用jQuery ...
$container.css({backgroundColor:'blue'});
因为css
函数是jquery对象的方法。当您执行$container[0]
时,您将获得与选择器匹配的第一个DOM节点,该选择器不是jquery对象。
尝试$container.css(...)
。
当您访问集合项时,不再具有jQuery方法,只有DOM元素。
您可以替换:
$container[0].css({backgroundColor:'blue'});
作者
$container.css({backgroundColor:'blue'});
[如果您还有一个具有相同css属性的div元素,
例如,让我们说下面的语句返回一个以上的结果:
var $container = $('.container'); // Has 3 results
并且您想到达特定元素的css属性,然后可以将dom元素转换为jquery元素,然后执行以下操作:
$($('.container').get(2)).css({ "background-color": "blue" });