假设我得到了subClass类的12个div,每个都以单个数字结尾:subClass-1、subClass-2等等。另外,对于这些类中的每一个,我都得到了相同的函数,例如:
function toggleAreas1() {
var $hide = $('.toggle-areas-1 > .row:visible');
$hide.fadeOut(function() {
if ($hide.next().length) {
$hide.next().fadeIn();
} else {
$hide.prevAll().last().fadeIn();
}
});
}但出于明显的原因,我不想使用12个不同的,但几乎相同的功能,当我可以很容易地使用一个,更普遍的。我在想一些类似的事情:
function toggleAreas1(index) {
for (i = 0; i < 12; i++) {
index = i++
var $hide = $('.toggle-areas-index > .row:visible');
}
$hide.fadeOut(function() {
if ($hide.next().length) {
$hide.next().fadeIn();
} else {
$hide.prevAll().last().fadeIn();
}
});
}但这当然不管用,因为我的js技能是不存在的。我该怎么办才能解决我的问题?
发布于 2015-12-04 09:49:42
function toggleAreas1() {
var $hide = $("[class^=toggle-areas] > .row:visible");
$hide.fadeOut(function() {
if ($hide.next().length) {
$hide.next().fadeIn();
} else {
$hide.prevAll().last().fadeIn();
}
});
}发布于 2015-12-04 09:47:08
您可以使用字符串连接来构建jQuery选择器:
for (i = 1; i <= 12; i++)
{
var $hide = $('.toggle-areas-' + i + ' > .row:visible'); // .toggle-areas-1, .toggle-areas-2 etc.
$hide.fadeOut(function() {
if ($hide.next().length) {
$hide.next().fadeIn();
} else {
$hide.prevAll().last().fadeIn();
}
});
}但是,为什么不直接给他们一个像toggle-areas这样的普通类呢?除了将添加到存在的之外,还可以添加这个类:
<div class="toggle-areas toggle-areas-1"></div>
<div class="toggle-areas toggle-areas-2"></div>
<div class="toggle-areas toggle-areas-3"></div>然后,您将能够同时完成以下两项任务:
// Affects all toogle-areas
$(".toogle-areas").fadeOut(function() {
if ($hide.next().length) {
$hide.next().fadeIn();
} else {
$hide.prevAll().last().fadeIn();
}
});和
// Affects only toogle-areas-2
$('.toggle-areas-2 > .row:first').show().nextAll().hide();发布于 2015-12-04 09:48:32
尝试更改var $hide =$(‘.> .row:visible');将var $hide =$(’.$hide-切换区域-‘+index+’> .row:visible');
https://stackoverflow.com/questions/34085207
复制相似问题