如何避免在Jquery中使用For / each重复以下代码行?
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATICFILES_DIRS = (
os.path.join('me_main/static'),
)
STATIC_URL = '/static/'
# Configure Django App for Heroku.
import django_heroku
django_heroku.settings(locals())
HTML:
$('.slider__section:nth-child(1)').hover(function(){
$('.slider__description').css("visibility", "hidden");
$('.slider__section:nth-child(1) .slider__description').css("visibility", "visible");
}, function(){
$('.slider__description').css("visibility", "visible");
});
我想将此应用于6个元素,但我不想重复此代码 尝试那样做,但是不起作用
<div class="slider">
<div class="slider__section">
<div class="slider__description">1</div>
<div>
<div class="slider__section">
<div class="slider__description">2</div>
<div>
<div class="slider__section">
<div class="slider__description">3</div>
<div>
<div class="slider__section">
<div class="slider__description">4</div>
<div>
<div class="slider__section">
<div class="slider__description">5</div>
<div>
<div class="slider__section">
<div class="slider__description">6</div>
<div>
<section class="fondo-slider"></section>
</div>
我想重复6次,此外,第n个孩子也会改变 我在等你的帮助。谢谢
答案 0 :(得分:0)
jQuery each
可以做到:
$('slider__section-pc').each(function(){
$(this).hover( //do your stuff here);
})
如果要在上述内容中添加一个函数,则需要引用this
才能传递给这些函数:
$('slider__section-pc').each(function(){
var x=$(this);
$(this).hover(ocultarDescription(x),MostrarDescription(x));
})
,然后在目标函数中使用 X ,例如:
function ocultarDescription(x){
$('.slider__description').css("visibility", "hidden");
x.find(".slider__description').css("visibility", "visible");
}
答案 1 :(得分:0)
采用原始代码,您可以使方法保持内联,但是使用this
而不是i
:
for (var i = 1; i <= 6; i++) {
$('.slider__section:nth-child(i)').hover(function() {
$('.slider__description').css("visibility", "hidden");
$(this).find('.slider__description').css("visibility", "visible");
}, function(){
$('.slider__description').css("visibility", "visible");
});
}
如果您希望将其应用于所有.slider__section
,则无需循环:
$('.slider__section').hover(function() {
$('.slider__description').css("visibility", "hidden");
$(this).find('.slider__description').css("visibility", "visible");
}, function(){
$('.slider__description').css("visibility", "visible");
});
如果您希望仅将其应用于前6个元素,并且不包含其他内容:
$('.slider__section:nth-child(-n+6)').hover(function() {
有关-n+6
的更多信息:https://www.w3.org/TR/selectors-3/#nth-child-pseudo