2015-09-28 45 views
0

我有一個表格的index.asp的Javascript遞增本身

<div class="wrapper pop-up" id="pop_up" style="display:none;"></div> 
<div class="log_in"> 
     <a href="/Login.asp" class="LogInBut" id="LogIn">Login</a> 
</div> 

的login.asp

<div class="authorize" id="authorizeID" > 

    <a href="#" id="authorize-closeBut" class="authorize-close"> 
     <img src="img/icons/cross.png" /> 
    </a> 

    <div id="response"> </div> 
    <div class="authorize-footer"> 
     <a href="/ForgotPassword.asp" class="LogInBut" id="passremainderBut">ForgotPassword</a> 
     <a href="/Register.asp" class="LogInBut" id="registrationBut">Registration</a> 
    </div> 
</div> 

ForgotPassword.asp

<div class="authorize" id="passremainderID" > 
    <a href="#" id="passremainder-closeBut" class="authorize-close"> 
     <img src="img/icons/cross.png" /> 
    </a> 
</div> 

我有一個JavaScript

$(".LogInBut").on('click', function(e) { 
     e.preventDefault(); 

     $.get($(this).attr('href'), function(data) { 
      alert($('#pop_up').length); 
      if ($('#pop_up').length) { 
       $('#pop_up').html(data).show(function() { 
        $('.authorize-close').click(function(e){  
         e.preventDefault(); 
         if ($('#pop_up').length) { 
          $('#pop_up').html(""); 
          $('#pop_up').hide(); 
         } 
        }); 
       }); 
      } 
     }); 
}); 

所以,如果我插入這個JavaScript到Index.asp頁面並單擊#LogIn,我得到彈出窗口與Login.asp和一次警報($('#pop_up')。長度); ;,如果我點擊.authorize-close窗口將關閉。如果我再次點擊#LogIn,我得到了相同的警告($('#pop_up')。);出現兩次,每次點擊#登錄時遞增。

那麼如何防止遞增並只顯示一次此警報?

+0

您應該委託事件,而不是http://learn.jquery.com/events/event-delegation/,而不是它的結合每個Ajax成功回調 –

回答

3

每當你點擊按鈕..你正在創建一個新的事件點擊#pop_up

$('.authorize-close').click(function(e){ 

它展示了兩次,因爲您創建的事件兩次。您需要刪除舊的事件,不是再次創造..行更改爲:

$('.authorize-close').unbind('click').bind('click',function(e){ 
+0

不發生任何影響,警報仍然遞增 –

+0

它不應該增加,沒有邏輯。有時是瀏覽器中的插件或將內容放入html中的東西。嘗試將此警報更改爲此代碼以檢查元素:for(i = 0; i <$('#pop_up')。length; i ++)alert $('#pop_up')[i] +「with id#」+ $('#pop_up')[i] .id +「,classes:。」+ $('#pop_up')[i] .className。 split('').join(',。')); –

+0

如果我放置$(「.LogInBut」)。unbind('click');在上次'})之前; ('。LogInBut「)。on('click',function(e){' –