[英]Issue on getting id from Selected HTML elements from Ajax GET response with jQuery
[英]Get a form ID from html response of an ajax call (jQuery)
以下是我的ajax
$.ajax({
url: formUrl,
complete :function(){
$("#formContainer").removeClass("some-class");
},
success: function(response){
$("#formContainer").html(response);
initFunctionOne();
initFunctionTwo();
initFunctionThree();
}
});
}
“響應”包含相應的 html forms 字符串格式,具體取決於正在加載的屏幕。 有什么方法可以從該響應中獲取表單 ID,以便我可以使用 switch case 語句僅調用其表單 ID 與 html 響應中的表單 ID 匹配的 function。
我正在初始化 document.getready 之外的三個函數,上面提到的 ajax 調用在 document.getready 內部
我嘗試使用 .find 和 .filter 但由於錯誤,它們都不起作用(錯誤:.filter 不是函數)
不確定這是否是一個好習慣,但我已經聲明了一個變量並使用索引設置了表單 ID 的 substring。 並使用我使用的變量 if else 條件來調用函數
由於您的響應字符串是 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”並在您打開它后檢查控制台日志你的瀏覽器。 這應該像上面一樣正常工作。
試試這個從響應 HTML 中獲取 id。
var formID = $($.parseHTML(response)).find('form').attr('id');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.