如何添加类到多个元素? [英] How to addClass to multiple elements?
问题描述
我使用这个位的javascript来添加一个类到多个元素。我试图引用多个div和addClass给他们。
code>< script>
$(function(){
if($(window).width()< 230){
$('#item1')。addClass('col1'); // max-width 80px
}
else
if($(window).width()> = 230&& $(window).width() 330){
$('#item1')。addClass('col2'); //最大宽度180px
}
else
{
$('#item1')。addClass('col3'); // max-width 280px
}
}
< / script>
它的工作原理如果我只有一个#item1在页面上,但似乎不想将该类添加到同一个div ID中存在的多个项目。我甚至尝试将类添加到同一个div类中存在的多个项,而不是id。任一个将是一个很好的解决方案,如果你可以计算出来。
$ b
我的HTML程式码
< div id =item1class =blue>
< label for =amount>价格范围:< / label>
< input type =textid =amountstyle =border:0; color:#f6931f; font-weight:bold; />
< div class =slider-range>< / div>
< / div>
< div id =item1class =blue>
< label for =amount2>价格范围:< / label>
< input type =textid =amount2style =border:0; color:#f6931f; font-weight:bold;/>
< div class =slider-range2>< / div>
< / div>
现在试图想出几个小时,所以我想我会问,任何人都可以指出我的方向正确。提前致谢。
ID应该是唯一的。尝试添加类,如item:
< div class =blue item>
... etc ...
< / div>
然后在您的JS中:
$('。item')。addClass('col1');
I'm using this bit of javascript to add a class to multiple elements. I trying to reference multiple divs and addClass to them. it Only works on the first one.
Javascript
<script>
$(function(){
if ( $(window).width() < 230 ) {
$('#item1').addClass('col1'); //max-width 80px
}
else
if ( $(window).width() >= 230 && $(window).width() < 330 ) {
$('#item1').addClass('col2'); //max-width 180px
}
else
{
$('#item1').addClass('col3'); //max-width 280px
}
});
</script>
it's working if I only have one #item1 on the page but it doesn't seem to want to add the class to multiple items that exist in the same div id. I even tried adding the class to multiple items that exist in the same div class rather than id. Either one would be a good solution for mw if you can figure it out.
My HTML code is
<div id="item1" class="blue">
<label for="amount">Price range:</label>
<input type="text" id="amount" style="border:0; color:#f6931f; font-weight:bold;" />
<div class="slider-range"></div>
</div>
<div id="item1" class="blue">
<label for="amount2">Price range:</label>
<input type="text" id="amount2" style="border:0; color:#f6931f; font-weight:bold;"/>
<div class="slider-range2"></div>
</div>
Been trying to figure this out for a few hours now so I thought I'd ask to see if anyone can point me in the right direction. Thanks in advance.
IDs should be unique. Try adding a class instead, like "item":
<div class="blue item">
...etc...
</div>
Then in your JS:
$('.item').addClass('col1');
这篇关于如何添加类到多个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!