當按下一個按鈕時,想打開一個新的標籤頁,可以使用window.open去實現
但是因爲使用window.open在新窗口或者新標籤頁中打開頁面,有可能被瀏覽器給攔截。
爲了解決這個問題,可以模擬鏈接被按下,然後打開鏈接。
但是在jQuery中,使用a.click(), a.trigger('click')等都不會引起鏈接默認事件被執行。
下面的代碼模擬生成了鏈接點擊事件,然後執行默認打開鏈接的事件。
- <html>
- <head>
- <meta http-equiv="Content-type" content="text/html; charset=utf-8">
- <title>Title</title>
- <script src="jquery.js"></script>
- <script type="text/javascript">
- $(function() {
- $("#btn").click(function() {
- //var a = $('a')[0];
- var a = $("<a href='http://www.apple.com' target='_blank'>Apple</a>").get(0);
- var e = document.createEvent('MouseEvents');
- e.initEvent( 'click', true, true );
- a.dispatchEvent(e);
- });
- });
- </script>
- </head>
- <body>
- <input type="button" value="Go to Apple" id="btn">
- </body>
- </html>
轉自:cppblog-http://www.cppblog.com/biao/archive/2010/08/21/124196.html