2013-04-09 43 views
0

我想調用這個函數,傳遞它作爲arg的錯誤類型,然後顯示消息。使用jQuery,我如何通過arg來運行,然後顯示來自預定義變量的消息

function msgDialog(msg) { 
    // Define messages 
    var errorMsg = "There has been an error. We are sorry about that."; 
    var loginMsg = "Something went awry with the login. Please try again."; 
    var uploadMsg = "Your upload failed. Please try again."; 
    var networkMsg = "You currently are not connected to the internet. Please connect and try again."; 
    alert(msg); 
} 

如何調用該函數msgDialog(loginMsg),並有我可以分配到正確消息的變種,然後做的東西?我在這裏提醒它,但我會以不同的方式顯示它。我知道我需要用arg值的值創建一個新的var,但不知道如何。謝謝。

+0

我不知道我理解你的問題。你能試着解釋另一種方式嗎? – 2013-04-09 02:09:26

+0

是的。我想調用該函數,並且我想根據發送的參數顯示一條消息。例如,如果我調用了msgDialog(loginMsg),我希望警報顯示「Something goes ...」,而不僅僅是arg var name。 – 2013-04-09 02:13:28

回答

4

這是純粹的JavaScript,沒有jQuery。試試這個:

var msgDialog = (function() { 
    var errors = { 
     errorMsg : "There has been an error. We are sorry about that.", 
     loginMsg : "Something went awry with the login. Please try again.", 
     uploadMsg : "Your upload failed. Please try again.", 
     networkMsg : "You currently are not connected to the internet. Please connect and try again." 
    } 

    return function(msg){ 
     alert(errors[msg]); 
    } 
})(); 

msgDialog('uploadMsg'); // alerts "Your upload failed. Please try again." 

你可以得到什麼事情here如果你以前沒關閉的JavaScript看到的想法。

+0

方式比我會說:)。你可以發佈使用說明嗎? – Doug 2013-04-09 02:22:10

+0

好耶很酷謝謝。我該如何調用這個var函數?例如,我有其他事件正在進行,並且如果事件失敗,我想從其他多個回調中調用該msgDialog函數。 – 2013-04-09 02:38:16

+0

您可以在代碼的最後一行看到使用示例。將其作爲所有其他函數進行調用,將要顯示的消息的名稱作爲字符串傳遞。 – Nicolas 2013-04-09 02:39:50