簡體   English   中英

如何讓兩個js函數一起工作?

[英]How do I get two js functions to work together?

我想使用JS登錄網站,然后將URL更改為同一網站上的其他頁面。 我有兩個職能,他們兩個都是獨立工作的,但不能一起工作。 我不知道如何編寫/組織這些功能,使它們可以一個接一個地執行。

function autoLogin() {

document.getElementById("userName").value = "username";
document.getElementById("pwd").value = "password";
document.getElementById("LoginButton").click();

}
autoLogin();

function nextPage() {
window.location.replace("https://www.website.com/page2");
}

nextPage();

您始終可以在第一個函數中添加回調,以調用傳入的第二個函數。例如:

function autoLogin(callback) {

    document.getElementById("userName").value = "username";
    document.getElementById("pwd").value = "password";
    document.getElementById("LoginButton").click();
    callback();
}

function nextPage() {
    window.location.replace("https://www.website.com/page2");
}

autoLogin(nextPage);

不過,這取決於您的LoginButton單擊,同時在后台同步執行某些操作。 如果要等待登錄中發生的任何事情先發生,則可能只想調用通過登錄按鈕調用的函數,而不是實際觸發單擊。 然后,您可以將回調傳遞給該函數;

假設您的LoginButton單擊調用了一個名為doLogin()的函數。 您可以將回調添加到該函數中,然后在調用之前檢查它在被調用時是否存在,以保持向后兼容性。

function doLogin(callback) {
   // get username and password and then asynchronously login

   if (callback) {
      callback();
   }
}

function autoLogin(callback) {

    document.getElementById("userName").value = "username";
    document.getElementById("pwd").value = "password";
    doLogin(callback);
}

function nextPage() {
    window.location.replace("https://www.website.com/page2");
}

autoLogin(nextPage);  //This calls autoLogin, which passes the callback to doLogin.                  
                      //Once doLogin is done, it calls nextPage.

我想以下內容將帶您進入新頁面。

document.getElementById("LoginButton").click();

因此,nextPage()將不會被調用。

也許,對於頁面2上加載的腳本,您可以在頁面加載時有條件地重定向到page2。

暫無
暫無

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

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