jQuery-防止其他“;点击“;功能

jQuery - Prevent other "on-click" functions

本文关键字:功能 点击 其他 jQuery-      更新时间:2023-09-26

我有一个简单的脚本,用户可以在其中加载两个不同的容器,其中包含一些不同的内容。

这是代码:

<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/

在这个例子中,试着快速点击"加载额外"answers"加载固定",你会看到两个容器中的内容都会显示出来。

使用现有代码最简单的方法可能是保存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目的是不寻常的,所以如果这没有转移到您的实际用例中,我也不会感到惊讶。