jquery:按类名获取元素并将css添加到每个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1812734/
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
jquery: get elements by class name and add css to each of them
提问by Eugene
I have a certain number of div boxes that all have the same class name. I am trying to apply something to them all but have no luck. The code I constructed so far is
我有一定数量的 div 框,它们都具有相同的类名。我正在尝试对它们应用一些东西,但没有运气。我到目前为止构建的代码是
$(document).ready(function(){
elements = $('div.easy_editor');
elements.each(function() { $(this).css("border","9px solid red"); });
//elements[0].css("border","9px solid red");
});
Could you please tell me what I am doing wrong
你能告诉我我做错了什么吗
回答by Vincent Ramdhanie
You can try this
你可以试试这个
$('div.easy_editor').css({'border-width':'9px', 'border-style':'solid', 'border-color':'red'});
The $('div.easy_editor')
refers to a collection of all divs that have the class easy editor already. There is no need to use each() unless there was some function that you wanted to run on each. The css() method actually applies to all the divs you find.
该$('div.easy_editor')
指具有类易编辑器已经所有div的集合。没有必要使用 each() ,除非您想在每个函数上运行某个函数。css() 方法实际上适用于您找到的所有 div。
回答by Guffa
What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.
jQuery 易于使用的原因在于您不必为每个元素应用属性。jQuery 对象包含一个元素数组,jQuery 对象的方法将相同的属性应用于数组中的所有元素。
There is also a shorter form for $(document).ready(function(){...})
in $(function(){...})
.
$(document).ready(function(){...})
in还有一个更短的形式$(function(){...})
。
So, this is all you need:
所以,这就是你所需要的:
$(function(){
$('div.easy_editor').css('border','9px solid red');
});
If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:
如果您希望代码适用于具有该类的任何元素,您只需在选择器中指定类而无需标记名称:
$(function(){
$('.easy_editor').css('border','9px solid red');
});