[英]How do I load html into a variable with jquery
我知道我可以將 html 加載到 div 中:
$("#my_div").load("http://www.mypage.com");
但我想做的是將 html 加載到一個變量中,例如:
my_var = load("http://www.mypage.com");
任何幫助都很棒。
我想循環一些項目,例如:
HLS.functions.LoadSideModules = function() {
HLS.sideModuleContent = new Object();
for(var i = 0; i < HLS.currentModuleConfig.POLICIES.POLICY.length; i++) {
for(var y = 0; y < HLS.currentModuleConfig.POLICIES.POLICY[i].PAGES.PAGE.length; y++) {
for(var POS in HLS.currentModuleConfig.POLICIES.POLICY[i].PAGES.PAGE[y]) {
var item = HLS.currentModuleConfig.POLICIES.POLICY[i].PAGES.PAGE[y][POS];
if(!HLS.sideModuleContent[item]) {
HLS.sideModuleContent[item] = j.get(HLS.config.K2GETMODULE + HLS.currentModuleConfig.POLICIES.POLICY[i].PAGES.PAGE[y][POS]);
}
}
}
}
};
$.get("http://www.mypage.com", function( my_var ) {
// my_var contains whatever that request returned
});
在下面,jQuery 將啟動一個 ajax 請求,該請求會觸發給定的 URL。 它還嘗試智能地猜測將要接收哪些數據(如果它是有效的 html,則不需要指定)。 如果您需要獲取另一種數據類型,只需將其作為最后一個參數傳遞,例如
$.get("http://www.mypage.com", function( my_var ) {
// my_var contains whatever that request returned
}, 'html'); // or 'text', 'xml', 'more'
您還可以在內存中創建一個元素並在其上使用 load() :
var $div = $('<div>');
$div.load('index.php #somediv', function(){
// now $(this) contains #somediv
});
優點是您可以使用選擇器(#somediv)指定要加載的 index.php 的哪一部分
雖然創建新元素是一種選擇,但您也可以克隆任何元素。 這將復制舊節點的所有屬性和值,正如它所說,“精確克隆”。
如果您只想復制 html 的特定部分,這也提供了從獲取的頁面填充特定元素層次結構中的所有內容(即,包括所有子元素)的靈活性。
例如,如果層次結構是 -
<div id='mydiv'>
<div>
<span>
...</span>
</div>
</div>
//...
var oldElement = document.getElementById('mydiv');
var newElement = oldElement.cloneNode(true);
/* #selector selects only that particular section & the '> *' enables to copy all of the child nodes under the parent #selector
Replace URL with the required value
function specification is optional... */
jQuery(newElement).load(URL+'#selector > *'[,function(response, status, xhr){}]);
//...
現在,您可以根據需要以編程方式處理變量 newElement(也可以使用本機 javascript,因為它是本機元素)。
function includeHTML_callBack(result){
var my_var = result;
}
function includeHTML(link, callBack) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callBack(this.responseText);
}
}
xhttp.open("GET", link, true);
xhttp.send();
return;
}
includeHTML("http://www.mypage.com", includeHTML_callBack);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.