jQuery 如何加载一些 html 并将其附加到 <body> 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1385641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:19:45  来源:igfitidea点击:

How can jQuery load some html and append it to the <body> element?

jqueryload

提问by omg

I tried the following:

我尝试了以下方法:

$.load("Views/chatBox.html").appendTo('body')

Console Output:

控制台输出:

TypeError: $.load is not a function 

EDIT: The answer should only be one line of code; that's enough, I think.

编辑:答案应该只有一行代码;够了,我想。

采纳答案by Gavrisimo

I dont understand why placing container at the bottom of body and loading external page into that is not what you need?

我不明白为什么将容器放在正文底部并将外部页面加载到其中不是您所需要的?

What you can try is this:

你可以尝试的是:

<script type="text/javascript">
    $(function() {
        $("#container").load("Views/chatBox.html",function(){
            $(this).clone().appendTo("body").remove();
        });
    });
</script>

But im not 100% sure about this code... :)

但我不是 100% 确定这段代码...... :)

回答by Rob Evans

Nope, all those answers are incorrect because they rely on having a separate container!

不,所有这些答案都不正确,因为它们依赖于有一个单独的容器!

Do this:

做这个:

$.ajax({
    url: "your.html",
    success: function (data) { $('body').append(data); },
    dataType: 'html'
});

回答by Kirill Fuchs

An alternative solution:

另一种解决方案:

jQuery('#AppendToMe').append( jQuery('<div>').load(...) );

This will append whatever you load into the #AppendToMe element.

这会将您加载的任何内容附加到 #AppendToMe 元素中。

回答by waffles

When I tried out GaVrA's solution I found it could be even simpler:

当我尝试 GaVrA 的解决方案时,我发现它可能更简单:

<script type="text/javascript">
    $(function() {
        $("#container").load("external.html").appendTo("body");;        
    });
</script>

I guess appentTo automatically removes a previous instance? Perhaps I'm missing something here?

我猜 appendTo 会自动删除以前的实例吗?也许我在这里遗漏了什么?

回答by Gavrisimo

Here you go:

干得好:

<script type="text/javascript">
    $(function() {
        $("body").load("Views/chatBox.html");
    });
</script>