繁体   English   中英

如何使用 jquery 将 html 加载到变量中

[英]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'

参考: http : //api.jquery.com/jQuery.get/

您还可以在内存中创建一个元素并在其上使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM