我有一个简单的脚本,用户可以在其中加载两个不同的容器,其中包含一些不同的内容。
这是代码:
<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 用于此 UI 目的并不常见,因此如果这没有转移到您的实际用例中,我不会感到惊讶。
关于javascript - jQuery - 阻止其他 "on-click"函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25593887/