[英]Conditionally open url in new tab via js
我有一個類似調查的Web應用程序,其中用戶選擇了許多復選框,然后按“提交”按鈕狀的鏈接
<!-- page: /survey -->
<form id="survey" method="post" action="/complete">
<!-- checkboxes, etc here -->
<a id="submit" class="button" href="#">Submit</a>
</form>
<script>
$('#submit').on('click', function (e) {
e.preventDefault();
//... other staff happens here
$('#survey').submit();
});
</script>
然后在服務器上處理該表單,並在/complete
頁面上將結果顯示給用戶。
我要實現的是在提交表單后有條件地打開一個新選項卡。 提交調查后,將在服務器上確定此條件和選項卡的url。
如果將window.open('...', '_blank')
插入初始/survey
頁面上的click-event handler中,則可以使其無條件工作:
$('#submit').on('click', function (e) {
e.preventDefault();
//... other staff happens here
window.open('http://example.com', '_blank'); // <---- this line
$('#survey').submit();
});
但是,如果我在/complete
頁面上使用window.open
,它將失敗:而是出現一個彈出警告。 可能是因為它未連接到任何用戶啟動的事件。
但是,就我而言,有一個用戶啟動的事件,但它發生在上一頁。 有什么辦法可以將此事件傳遞給新頁面(顯然,新頁面位於相同的域名,協議等上)。 可能還有另一種方法?
做您想做的正確方法是更改標記:
<form id="survey" method="post" action="/complete">
<!-- checkboxes, etc here -->
<button type="submit" id="submit" class="button">Submit</button>
</form>
然后在JavaScript中,監聽submit
事件。 默認情況下,這將允許本機功能(例如隱式提交(文本字段中的輸入鍵)或單擊提交按鈕的中鍵)起作用。
現在這里是一些重要的部分:
target
屬性。 $('#survey').on('submit', function (e) {
if (!checkValidity(...)) {
e.preventDefault();
return;
}
//other stuff happens
var newTab = shouldOpenInNewTab(...);
$(this).attr('target', newTab ? '_blank' : '');
});
這樣做將允許瀏覽器使用其默認行為。 它與跨瀏覽器兼容,並且可以訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.