簡體   English   中英

go 到頁面並打開模態 javascript

[英]go to page and open modal javascript

目標是 go 到一個頁面並從該頁面顯示一個模式。

有沒有辦法在頁面成功加載后執行?

//load page
window.location.href = 'foobar.html';

//wait until page is ready then open modal?
$(window).ready(function () {
  console.log('did it work?');
  $('#someModal').modal('show');
});

我在 html 頁面中列出了 javascript 文件,但這不起作用。 一切都發生在與初始頁面相同的文檔 window 中。

回答

我決定獲取以前的 url 並搜索 substring 以觸發模態顯示在第二頁上。

//first js script for the first html page
window.location.href = 'foobar.html';

//second js script for the second html page
$(document).ready(function () {

    var prev_url = document.referrer;

    if (prev_url.includes('substring')){
        $('#someModal').modal('show');
    }
});

感謝您的建議。

我想了一種方法來讓它工作,在第二頁文檔重新加載。 我會得到最后一個 url 字符串,看看它是否包含 substring,如果是。 顯示模態:似乎正在工作:)

$(document).ready(function () {

    var prev_url = document.referrer;

    if (prev_url.includes('substring')){
        $('#someModal').modal('show');
    }
});

不幸的是,javascript 只存在於頁面加載之間,每次新的頁面加載都會清除所有正在執行的 javascript 代碼。 如果要模擬頁面加載,可以使用 History api,它將新條目推送到瀏覽器的后退按鈕上,然后運行代碼。 而不是為window.location分配值,您需要調用pushState並按照鏈接中的說明給它一些 arguments ,然后繼續調用您的模態代碼。

例如,

window.history.pushState({}, window.document.title, 'foobar.html');
$('#someModal').modal('show');

您應該分開腳本。 第一頁:

 $(document).ready(function () {
window.location.href="foobar.html";
});

第二頁:

 $(document).ready(function () {
     $('#someModal').modal('show');
});

我希望這對你有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM