簡體   English   中英

在調用另一個函數之前,請確保已加載JS文件並調用了JS函數

[英]Make sure JS file is loaded and JS function is called BEFORE calling another function

我有一個跟蹤代碼無法正常運行的問題,因為在加載所需的JS腳本和函數之前調用了該跟蹤代碼。 情況如下:

成功提交表單(WordPress上為CF7)后,立即調用以下功能。

    function fn111Rooms(){
       var email_address = document.getElementsByName("your-email")[0].value;
       fnTransaction('Room booked', 'userid=' + email_address);
       location.replace('http://example.com/thank-you');
     }

但是問題是,需要預先調用以下腳本+函數,以使所有功能正常運行

<script type="text/javascript" src="http://www.example.com/Tracking.js"></script>
<script>fnPageHit('4ddc12d4344');</script>

此位放置在每個頁面的部分中,但在表單提交時不會再次調用,因為該表單是通過AJAX提交的(我相信這就是問題所在)。

如何將腳本包含到fn111Rooms中,並確保正確並按順序調用所有內容。 真抱歉,這是一個愚蠢的問題,但是JS仍然不時使我感到困惑。

編輯:這項工作嗎?

function fn111Rooms(){

    // Loads the script
    var fileref=document.createElement('script')
    fileref.setAttribute("type","text/javascript")
    fileref.setAttribute("src", "http://www.example.com/Tracking.js")

    // Calls the required function
    fnPageHit('4ddc12d4344');

    // Does the rest
    var email_address = document.getElementsByName("your-email")[0].value;
    fnTransaction('Room booked',    'userid=' + email_address);
    location.replace('http://example.com/thank-you');
 }

然后只需在提交表單時調用一個函數即可。

您可以看一下jQuery.when()

假設您有一個必須執行的功能

function yourFirstFunction(){ 
    $.post('/somewhere'); 
} 

在第一個結束后的第二個

function yourOtherFunction() {
    //stuff
}

然后您可以使用以下構造

$.when( yourFirstFunction() ).then(function(data) { 
    yourOtherFunction()
})

例如,當您的yourFirstFunction完成(ajax請求完成)后,您的yourSecondFunction將被執行

一種方法是應用具有一定間隔的無限循環並檢查以下條件

fnPageHit && fnPageHit('4ddc12d4344');

因此,當evr加載時,在其他情況下,u將獲得功能。fnPageHit將是未定義的,因此不會執行,也不會導致錯誤

暫無
暫無

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

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