[英]jQuery - Prevent other “on-click” functions
我有一个简单的脚本,用户可以在其中加载两个不同的容器,这些容器中包含一些不同的内容。
这是代码:
<div id="t-loader"></div>
<div class="media load-fixed active">
Load Fixed
</div>
<br />
<div class="media load-extra">
Load Extra
</div>
<br />
<div class="fixed-ads">
FIXED ADS IN HERE!!
</div>
<div style="display: none;" class="extra-ads">
EXTRA ADS IN HERE!!
</div>
和jQuery:
$('.load-extra').click(function() {
$(this).addClass('active');
$('.load-fixed').removeClass('active');
$('.fixed-ads').hide();
$('#t-loader').show().html('loader');
setTimeout(
function()
{
$('#t-loader').hide();
$('.extra-ads').show();
}, 2000);
});
$('.load-fixed').click(function() {
$(this).addClass('active');
$('.load-extra').removeClass('active');
$('.extra-ads').hide();
$('#t-loader').show().html('loader');
setTimeout(
function()
{
$('#t-loader').hide();
$('.fixed-ads').show();
}, 2000);
});
问题是,每当有人单击.load-extra
和.load-fixed
两者都将显示在页面中。
我该怎么办,所以只要有人单击.load-extra
或.load-fixed
,只有其中一个会显示?
我在这里创建了一个jsFiddle: http : //jsfiddle.net/j21oofwx/
在示例中,尝试快速依次单击“额外加载”和“固定加载”-您会看到两个容器中的内容都将显示。
现有代码最简单的方法可能是保存setTimeout并在每次单击按钮时将其清除-http: //jsfiddle.net/uegt5opm/
var setTimer = null;
$('.load-extra').click(function() {
$(this).addClass('active');
$('.load-fixed').removeClass('active');
$('.fixed-ads').hide();
$('#t-loader').show().html('loader');
clearTimeout(setTimer);
setTimer = setTimeout(function(){
$('#t-loader').hide();
$('.extra-ads').show();
}, 2000);
});
$('.load-fixed').click(function() {
$(this).addClass('active');
$('.load-extra').removeClass('active');
$('.extra-ads').hide();
$('#t-loader').show().html('loader');
clearTimeout(setTimer);
setTimer = setTimeout(function(){
$('#t-loader').hide();
$('.fixed-ads').show();
}, 2000);
});
尽管在“真实”设置中为此用户界面目的使用setTimeout是不寻常的,所以如果这不转移到您的实际用例中,我也不会感到惊讶。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.