我需要測試窗體的值onsubmit
是否爲函數。格式通常是onsubmit="return valid();"
。有沒有辦法判斷這是一個函數,如果它是可調用的?使用typeof只是返回它是一個字符串,這對我沒有多大幫助。測試值是否爲函數
編輯:當然,我明白「return valid();」是一個字符串。我已將replace
記錄爲「valid();」,甚至「valid()」。我想知道這些是否是一種功能。
編輯:下面是一些代碼,這可能有助於解釋我的問題:
$("a.button").parents("form").submit(function() {
var submit_function = $("a.button").parents("form").attr("onsubmit");
if (submit_function && typeof(submit_function.replace(/return /,"")) == 'function') {
return eval(submit_function.replace(/return /,""));
} else {
alert("onSubmit is not a function.\n\nIs the script included?"); return false;
}
});
編輯2:這裏是新的代碼。看來我仍然必須使用eval,因爲調用form.submit()不會觸發現有的onsubmits。
var formObj = $("a.button").parents("form");
formObj.submit(function() {
if (formObj[0].onsubmit && typeof(formObj.onsubmit) == 'function') {
return eval(formObj.attr("onsubmit").replace(/return /,""));
} else {
alert("onSubmit is not a function.\n\nIs the script included?");
return false;
}
});
關於可能如何做得更好的建議?
這是行不通的。當onsubmit也是非空字符串時,if將斷言爲TRUE。 – Seb 2009-04-28 14:48:59
一個可怕的測試方法,如果某個東西是一個函數 - 如前所述,並且更清晰:任何「真理」都會導致此代碼「做東西」,而這可能不是預期的結果。如果將this.onsubmit設置爲值5或「hello」或JavaScript中的任何其他值爲true的值,您將會遇到意外的行爲。 – 2009-04-28 20:22:20
問題的主題是詢問如何檢查是否存在問題。這就是我所說的 - 不多也不少。 – Kon 2009-04-29 20:33:19