我有以下HTML代码:
<ul class="top-attractions-prague">
<li class="homepage-carousel-item">
<div class="hci_thumb_abrupt" style="background-image:url(/86/28655.jpg)">
<div class="hci_label_abrupt">
<div class="hci_label-container_abrupt">
<div class="hci_label-subcontainer_abrupt">
<p class="hci_label_txt_abrupt">You'll love food</p>
</div>
</div>
</div>
</div>
<a class="hci_name_abrupt" href="/discover/country/it.html?">Prague</a>
</li>
<li class="homepage-carousel-item">
<div class="hci_thumb_abrupt" style="background-image:url(/86/28655.jpg)">
<div class="hci_label_abrupt">
<div class="hci_label-container_abrupt">
<div class="hci_label-subcontainer_abrupt">
<p class="hci_label_txt_abrupt">You'll love food</p>
</div>
</div>
</div>
</div>
<a class="hci_name_abrupt" href="/discover/country/it.html?">Prague</a>
</li>
<li class="homepage-carousel-item">
<div class="hci_thumb_abrupt" style="background-image:url(/86/28655.jpg)">
<div class="hci_label_abrupt">
<div class="hci_label-container_abrupt">
<div class="hci_label-subcontainer_abrupt">
<p class="hci_label_txt_abrupt">You'll love food</p>
</div>
</div>
</div>
</div>
<a class="hci_name_abrupt" href="/discover/country/it.html?">Prague</a>
</li>
</ul>
我想将类Active添加到以下部分:
".hci_thumb_abrupt"
".hci_label_abrupt"
".hci_label-container_abrupt"
".hci_label-subcontainer_abrupt"
".hci_label_txt_abrupt"
我写了快速解决方案,但我不喜欢重复循环:
$(function () {
var f = {
$thumb: ".hci_thumb_abrupt",
$label: ".hci_label_abrupt",
$container: ".hci_label-container_abrupt",
$subcontainer: ".hci_label-subcontainer_abrupt",
$label_txt: ".hci_label_txt_abrupt"
};
$('.homepage-carousel-item').hover(
function () {
$.each(f, function (i, val) {
$(val).addClass("active");
});
},
function () {
$.each(f, function (i, val) {
$(val).removeClass("active");
});
}
);
});
有人能为我提供更优雅的解决方案吗?我试过这样的事情:
$(function (c, b, a) {
c.fn.textLabel = function (d) {
var w = {
$item: ".homepage-carousel-item",
$label: ".hci_thumb_abrupt"
};
var e = c.extend({}, w, d);
return this.each(function () {
c(this).bind({
mouseover: function () {
c(this).addClass("active").find("*").addClass("active");
alert('bastead');
},
mouseleave: function () {
c(this).removeClass("active").find("*").removeClass("active");
}
})
})
}
});
但是第二个代码没有任何反应,无法完全调试它。
注意ACTIVE类需要单独应用于每个<li>
答案 0 :(得分:0)
好的,请在评论后开始
你有两种选择方式来做到这一点
1st:使用
$(this).find('div').addClass('active');
所以你的代码将是
$('.homepage-carousel-item').hover(
function () {
$(this).find('div').addClass("active");
},
function () {
$(this).find('div').removeClass("active");
}
);
});
这段代码会将Active类添加到你所拥有的li里面的所有div
2-为要添加活动类的每个元素添加类
例如
<div class="to_add_active hci_label-subcontainer_abrupt">
注意:您可以将to_add_active添加到要向其添加类Active的任何元素
并像这样使用
$(this).find('.to_add_active').addClass("active");
下一个演示解释