jQuery addClass 到所有具有 Class 的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5860649/
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 addClass to all Elements with Class
提问by ToddN
I want to addClass 'strike' to class 'priceis' IF class 'specialprice' exists. Currently it is only putting it on the FIRST of the elements not every element that appears in the page. I need it to check for all elements with class 'specialprice'.
如果存在“specialprice”类,我想将“strike”类添加到“priceis”类中。目前它只是将它放在元素的第一个而不是页面中出现的每个元素上。我需要它来检查所有具有“特价”类的元素。
<font class="pricecolor colors_productprice specialprice">
<span class="PageText_L483n">
<font class="text colors_text"><b>Regular Price:<br> </b></font>
<span class="priceis">,492<sup>.38</sup></span></span>
</font>
$('.specialprice').find('.priceis').addClass('strike');
回答by Jonas
$('.specialprice.priceis').addClass('strike');
?
$('.specialprice.priceis').addClass('strike');
?
回答by Alex K
maybe something like this? still not sure about the explanation of your question, not clear..
也许是这样的?仍然不确定您的问题的解释,不清楚..
$(function() {
$('.specialprice').each(function() {
$(this).find('.priceis').addClass('strike');
});
}
EDIT: just realized maybe you wanted it like this?
编辑:刚刚意识到也许你想要这样?
$('.specialprice').each(function() {
$(this).find('*').addClass('strike');
});
回答by BrunoLM
Your HTML is wrong
你的 HTML 是错误的
<span id="priceis">
You probably meant to set class
instead of id
.
您可能打算设置class
而不是id
.
<span class="priceis">
Your current code will work if you fix your HTML.
You might want to see this answer, it explains why a script doesn't work when included before the DOM elements.
您可能希望看到这个答案,它解释了为什么脚本在 DOM 元素之前包含时不起作用。
回答by Seth
$('.priceis').each(function(i, item) {
var $item = $(item);
if( $item.hasClass('specialprice') || $item.parents('.specialprice') )
{
$item.addClass('strike');
}
});
回答by Naftali aka Neal
Try this:
尝试这个:
$('.specialprice').has('.priceis').addClass('strike');