【问题标题】:jQuery $each fadeIn fadeOutjQuery $每个淡入淡出淡出
【发布时间】:2021-03-05 16:16:21
【问题描述】:
除了一件事,一切都很好,我想要这样当你已经看到 .show 类时,当你点击另一个 #c- div 时,它会再次消失。
http://jsfiddle.net/7KdR6/1/
$('[id^="c-"]').each(function(i){
$this = $(this);
$(this).text(i);
$(this).on('click',function(){
$('.show').fadeIn().text(i);
event.stopPropagation();
});
})
$(document).on('click', function(){
$('.show').fadeOut();
});
【问题讨论】:
标签:
javascript
jquery
jquery-events
dom-manipulation
【解决方案1】:
您的问题之一是您没有停止传播,因为没有定义event。您必须使用 click 处理程序的参数。 编辑: 实际上,event 似乎是自动传递的——我以前没有意识到这一点。但是,我仍然认为如果要使用事件对象,最好将它作为参数 - jQuery 在他们的示例中做到了这一点,这使得它更加明显。
我还注意到您正在缓存 this,但随后没有使用该缓存的 var。这意味着每次你写$(this),它都必须重新包装那个jquery对象。
然后你可以有一个fadeOut 并使用fadeIn 作为fadeOut 的回调。这样,如果.show 元素已经显示,它将首先淡出。我会这样写:
$('[id^="c-"]').each(function (i) {
$this = $(this);
$this.text(i);
$this.on('click', function (event) {
event.stopPropagation();
$show = $(".show");
$show.fadeOut(function () {
$show.fadeIn().text(i);
});
});
})
Fiddle
【解决方案2】:
在可见元素上使用fadeIn之前需要隐藏元素
$('[id^="c-"]').each(function (i) {
var $this = $(this);
$this.text(i);
$this.on('click', function () {
$('.show').hide().fadeIn().text(i);
event.stopPropagation();
});
})
演示:Fiddle