javascript 未捕获的类型错误:div.css 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31065494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: div.css is not a function
提问by Ethyl Casin
I was trying to dynamically change the background-colorof the div but unfortunately I cant seem to make it work! Please let me know what's wrong with my codes.
我试图动态更改background-colordiv 的,但不幸的是我似乎无法让它工作!请让我知道我的代码有什么问题。
Code:
代码:
<!doctype html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
var categorydivs = $(".category-container");
$.each(categorydivs,function(index,div){
div.css("background-color","yellow");
});
});
</script>
</head>
<body>
<div id="main-container">
<div class="category-container">
Category 1
</div>
<div class="category-container">
Category 2
</div>
</div>
</body>
</html>
After running the codes above it will throw an error: Uncaught TypeError: div.css is not a function. Why?
运行上面的代码后,它会抛出一个错误:Uncaught TypeError: div.css is not a function。为什么?
回答by Tushar
divinside eachis not the jQuery objectit is the HTMLelement, so you cannot call jQuery methods on it.
div里面each不是 jQueryobject它是HTML元素,所以你不能在它上面调用 jQuery 方法。
You can use $(this)inside eachto get the current divinstance.
您可以使用$(this)insideeach来获取当前div实例。
$(document).ready(function () {
var categorydivs = $(".category-container");
$.each(categorydivs, function (index, div) {
$(this).css("background-color", "yellow");
});
});
You don't need to loop for adding css to all elements. Use following code:
您不需要循环将 css 添加到所有元素。使用以下代码:
$(document).ready(function() {
$(".category-container").css('background-color', 'yellow');
});
回答by WisdmLabs
Try to use:-
$(this).css("background-color","yellow");instead of div.css("background-color","yellow");
尝试使用:-
$(this).css("background-color","yellow");而不是div.css("background-color","yellow");
回答by Martin Cisneros Capistrán
The line: div.css("background-color","yellow");
该行: div.css("background-color","yellow");
Change to: $(div).css("background-color","yellow");
更改为: $(div).css("background-color","yellow");
Regards.
问候。

