以下是我的ajax
$.ajax({
url: formUrl,
complete :function(){
$("#formContainer").removeClass("some-class");
},
success: function(response){
$("#formContainer").html(response);
initFunctionOne();
initFunctionTwo();
initFunctionThree();
}
});
}
“回應”包含字串格式的相應 html 表單,具體取決于正在加載的螢屏。有什么方法可以從該回應中獲取表單 ID,以便我可以使用 switch case 陳述句僅呼叫表單 ID 與 html 回應中的表單 ID 匹配的函式。
我正在初始化 document.getready 之外的三個函式,上面提到的 ajax 呼叫在 document.getready 內部
我嘗試使用 .find 和 .filter 但由于錯誤,它們都沒有作業(錯誤:.filter 不是函式)
uj5u.com熱心網友回復:
不確定這是否是一個好習慣,但我已經宣告了一個變數并使用索引設定了表單 ID 的子字串。并使用我使用的變數 if else 條件來呼叫函式
uj5u.com熱心網友回復:
試試這個從回應 HTML 中獲取 id 。
var formID = $($.parseHTML(response)).find('form').attr('id');
uj5u.com熱心網友回復:
由于您的回應字串是 HTML 格式,您可以通過使用 DOMParser 以一種很好、簡單和干凈的方式獲取表單 ID,如下所示:
//shorter version
var formId = (new DOMParser()).parseFromString(response, "text/html").forms[0].id; //done
或者,下面給出了一個更詳細和可重用的版本,并帶有一個示例:
//Use DOMParser to convert the HTML string to a valid HTML document object
function parseHTMLString(htmlString) {
const parser = new DOMParser();
return parser.parseFromString(htmlString, "text/html");
};
//Get the form id of the first form element from the doc object.
//You may also return an array of form ids if you have multiple forms in your response.
function getFirstFormIdFromParsedHtmlString(doc) {
//console.log(doc.forms);
return doc.forms[0].id;
}
//this is how to use it
//example response string
var response = '<form id="myForm1"></form>';
const myDocument = parseHTMLString(response);
const formId = getFormIdFromParsedHtmlString(myDocument);
console.log('formId:', formId); //prints 'formId: myForm1'
如果您想測驗上述內容,您只需將此代碼片段復制/粘貼<script>...</script>
到一個空白 HTML 檔案“example.html”中,然后在瀏覽器中打開此檔案后檢查控制臺日志。這應該像上面一樣正常作業。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/504792.html
標籤:javascript html jQuery 阿贾克斯
下一篇:當該鍵的值更改時,如何保留該鍵?