2016-08-08 6 views
2

を働いていない私は、異なる期間で私のWebページ上の各アラートを閉じautoにシンプルなjQueryのスクリプトを書きました。ブートストラップのアラートの自動閉鎖が

これは私のjQueryのコードです:ここで

$(function() { 
     var alert = $('div.alert[auto-close]'); 
     alert.each(function() { 
      var time_period = $(this).attr('auto-close'); 
      setTimeout(function() { 
       $(this).alert('close'); 
      }, time_period); 
     }); 
    }); 

は私の2つのサンプルアラートです:

<div class="alert alert-danger alert-dismissible" role="alert" auto-close="3000"> 
       <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
       alert one 
      </div> 
<div class="alert alert-success alert-dismissible" role="alert" auto-close="5000"> 
       <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
       alert two 
      </div> 

各アラートは、アラート閉鎖期間として使用されている値を持つカスタム属性を持っています。

何らかの理由でアラートの終了が機能していません。

+0

試し: 'VAR this_alert = $(この);' TIME_PERIODするvar以下。 'setTimeOut'コールバックスコープ内で' $(this)).alert( 'close'); 'do:' this_alert.alert( 'close') ' – dMd

+0

' $(this) 'とは異なります。それをキャッシュする。下の私の答えをチェックしてください。 – Iceman

+0

ええ、今私はエラーの原因を理解しています。 – Great9

答えて

1

$(this)は、setTimeoutスコープ内で変更されました。それを変数にキャッシュします。私の例ではthatです。

$(function() { 
    var alert = $('div.alert[auto-close]'); 
    alert.each(function() { 
    var that = $(this); 
    var time_period = that.attr('auto-close'); 
    setTimeout(function() { 
     that.alert('close'); 
    }, time_period); 
    }); 
}); 

WORKING SNIPPET:

$(function() { 
 
    var alert = $('div.alert[auto-close]'); 
 
    alert.each(function() { 
 
    var that = $(this); 
 
    var time_period = that.attr('auto-close'); 
 
    setTimeout(function() { 
 
     that.alert('close'); 
 
    }, time_period); 
 
    }); 
 
});
<script src="https://code.jquery.com/jquery.min.js"></script> 
 
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> 
 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> 
 
<div id="moo" class="alert alert-danger alert-dismissible" role="alert" auto-close="3000"> 
 
    <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span> 
 
    </button> 
 
    alert one 
 
</div> 
 
<div class="alert alert-success alert-dismissible" role="alert" auto-close="5000"> 
 
    <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span> 
 
    </button> 
 
    alert two 
 
</div>

+0

うわー、アイスマンに感謝します。あなたは命の恩人です:)私は7分後に答えを受け入れます。 – Great9

+0

@JecobBomanうれしかった..! – Iceman

関連する問題