我想根据文本内容的含义为div添加一个类。然而,我目前遇到的问题是有多个容器,因此同一个类被应用于所有容器。我很确定这个问题的解决办法是如何正确使用"这个"也许是一个循环遍历每个元素与我正在寻找的类,但我不知道如何实现它。
我有三种类型的文字内容:
"特别活动"应该检查并获得特殊事件类。
"每日促销"应该参加每日推广课。
" Players Club Incentive"应该是奖励类。
var promotion = $("div.promotion-type").html();
if(promotion === "Special Event"){
$("div.promotion-type").addClass("special-event");
}
else if(promotion === "Daily Promotion"){
$("div.promotion-type").addClass("daily-promotion");
}
else if(promotion === "Players Club Incentive"){
$("div.promotion-type").addClass("incentive");
}
我明白这是错误的。它正在检查内容,然后将类添加到所有内容中。不是我想要的。我只是想检查单个容器,然后根据内容添加适当的类。
其中一个事件的HTML示例:
<li class="hidden-xs col-sm-6 col-md-4">
<div class="calendar-event">
<div class="event-details-container">
<div class=" col-xs-4 calendar-thumbnail">
<a href="/warroad-calendar/canadian-day">
<img src="/_images/warroad/calendar/may-june-2014/canadianDay.jpg" border="0" alt="" />
</a>
</div>
<h3><a href="/warroad-calendar/canadian-day">Canadian Day</a></h3>
<h4>8 a.m. - 6 p.m.</h4>
<strong></strong><br />
<div class="hidden-xs hidden-sm hidden-md hidden-lg promotion-type">Daily Promotion</div>
</div>
</div>
</li>
JS小提琴:
直播页面:
http://sevenclanscasino.designangler.com/warroad/warroad-calendar
答案 0 :(得分:2)
有很多方法可以解决这个问题。
试试这个:
$("div:contains('Special Events')").addClass('special-events');
$("div:contains('Daily Promotion')").addClass('daily-promotion');
$("div:contains('Players Club Incentive')").addClass('incentive');
另一种方法:
var highlights = {
"Special Events": "special-events",
"Daily Promotion": "daily-promotion",
"Players Club Incentive": "incentive"
}
$("div.promotion-type").each(function() {
$(this).addClass(highlights[$(this).html()]);
});
答案 1 :(得分:1)
你可以像这样循环 - http://jsfiddle.net/jayblanchard/Q8hju/2/
$('div.promotion-type').each(function () {
var promotion = $(this).html();
console.log(promotion);
if (promotion === "Special Event") {
$(this).addClass("special-event"); // this is the only one with a class created for it so far
} else if (promotion === "Daily Promotion") {
$(this).addClass("daily-promotion");
} else if (promotion === "Players Club Incentive") {
$(this).addClass("incentive");
}
});
答案 2 :(得分:0)
你可以循环完成。 fiddler example
$("div.promotion-type").each(function(index, element){
var item = $(this);
var promotion = item.text();
if(promotion === "Special Event"){
item.addClass("special-event");
}
else if(promotion === "Daily Promotion"){
item.addClass("daily-promotion");
}
else if(promotion === "Players Club Incentive"){
item.addClass("incentive");
}
});
答案 3 :(得分:0)
$("div.promotion-type").each(function(i){
var $el = $(this),
promotion = $el.text();
if(promotion === "Special Event"){
$el.addClass("special-event");
}else if(promotion === "Daily Promotion"){
$el.addClass("daily-promotion");
}else if(promotion === "Players Club Incentive"){
$el.addClass("incentive");
}
});