2014-02-13 66 views
0

我試圖觸發點擊事件的鏈接從一個點擊處理程序中的同一鏈接。我想要停止導航鏈接,直到用戶收到某些操作的通知。一旦行動完成,鏈接應該正常導航。觸發點擊從點擊處理程序內

請參閱下面的測試用例。

<!DOCTYPE html> 
<html> 
    <head> 
     <title></title> 
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> 
    </head> 
    <body> 
     <script language="javascript" type="text/javascript"> 
      $(function() { 
       $("#test").click(function (e) { 
        var lnk = $(this); 

        if (lnk.data("checked") != true) { 

         var notice = $('<a href="#">Continue</a>'); 
         $('body').append(notice); 

         notice.click(function (e) { 
          lnk.data("checked", true); 
          lnk.click(); 

          return false; 
         }); 

         return false; 
        } 

        alert("should navigate now"); 
       }); 
      }); 
     </script> 

     <a id="test" href="http://www.google.com">Test</a> 

    </body> 
</html> 

該示例的預期行爲是;

  • 測試點擊
  • 繼續出現
  • 繼續點擊
  • 頁面導航到 '測試'

的href相反,被點擊繼續,警報 '現在應該導航'顯示,但瀏覽器不執行任何操作。

+1

手動觸發可能不會觸發元素 –

+0

檢查類型lnk.data(「選中」)''的的默認行爲,它可能被認爲不是'falsy' –

+0

@ArunPJohny你有參考嗎? – Alex

回答

1

嘗試使用DOM元素

notice.click(function (e) { 
     lnk.data("checked", true); 
     lnk[0].click(); 
     // ^^^^ 
     return false; 
    }); 

DEMO

+0

這可行。你知道爲什麼嗎?推測jQuery是干擾,它是否有某種'潛在的無限循環'檢查? – Alex

+0

@Alex我不確定爲什麼jQuery不允許鏈接的默認行爲,但我認爲它是有意的。 – Anton

+0

@Alex在這裏找到了一些信息http://stackoverflow.com/a/5867423/1696560'您只能觸發jQuery創建的點擊。這是jQuery的一個可愛的小怪癖。' – Anton

0

只需在警報後添加document.location.href = lnk.attr('href');

我想,問題出現了,因爲警報會中斷回調。

0

不知道這是你想要的,但嘗試重寫你這樣的代碼:

$(function() { 
    $("#test").click(function (e) { 
     e.preventDefault(); 
     if ($(this).data("checked") != true) { 
      var notice = $('<a class="link" href="#">Continue</a>'); 
      $('body').append(notice); 
     } 
     alert("should navigate now"); 
    }); 

    $(document).on('click', '.link', function (e) { 
     $("#test").data("checked", true); 
     window.location = $("#test").attr('href'); 
    }); 
}); 
0

我知道這觸發點擊已經很老了,但我想從現在開始爲那些發現這個問題和答案的人做出貢獻。

如果您嘗試確認用戶是否想離開某個網站,請考慮window.onbeforeunload事件處理程序。您可以在類似警報的消息框中輸入顯示給用戶的字符串消息。

<script> 
window.onbeforeunload = function (e) { 
    e = e || window.event; 

    // For IE and Firefox prior to version 4 
    if (e) { 
     e.returnValue = 'Sure?'; 
    } 

    // For Safari 
    return 'Sure?'; 
}; 
</script> 

檢查第一個答案在這裏:點擊事件的 Confirmation before closing of tab/browser