使用 javascript 将 HTML 附加到正文的末尾
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2488725/
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
Appending HTML to end of body using javascript
提问by ming yeow
I have several templates for faceboxes (lightbox) that I need at different points of the application. These are stored in different partials and files.
我有几个模板(灯箱),我需要在应用程序的不同点。这些存储在不同的部分和文件中。
I will initialize different javascript functions in accordance to which ones I need. The question is, what is the best way to append the external HTML page into my body using javascript?
我将根据需要初始化不同的 javascript 函数。问题是,使用 javascript 将外部 HTML 页面附加到我的正文中的最佳方法是什么?
回答by ?a?da? Tekin
Since you tagged the question with it, here's a jQuery solution.
由于您用它标记了问题,因此这是一个 jQuery 解决方案。
$("body").append("text");
Remember that the parameter can also be a DOM element. So you can do this :
请记住,参数也可以是 DOM 元素。所以你可以这样做:
var p = $("<p/>").text("a paragraph");
$("body").append(p);
回答by Luca Filosofi
the easy way with jQuery is:
使用 jQuery 的简单方法是:
$('#result').load('test.html');
<div id="result"><!--/ Hold My Data! /--></div>
obviously you can change #resultwith body
显然你可以用身体改变#result
回答by Sam
Also you can try some templates library.. Like handlebar and underscore..
你也可以尝试一些模板库..像把手和下划线..
and append in the el provided by backbone.js
并附加到backbone.js 提供的el
回答by gargAman
Suppose you want to append this html in your template, then you can use the below code according to your application Consider the code
假设你想在你的模板中附加这个 html,那么你可以根据你的应用程序使用下面的代码 考虑代码
Example 1:
示例 1:
rowData += '<div style="width: 130px;">'+param1+'</div>';
rowData += '<div style="width: 130px;">'+param2+'</div>';
$('#ID').html(rowData);
and please make sure that the js should be include in that file. Here is the information of variable used above:
并请确保该 js 应包含在该文件中。这是上面使用的变量的信息:
row data- the html that you want to append,
行数据- 要附加的 html,
param- if you want to show the value of java script variable on browser dynamically,
param- 如果要在浏览器上动态显示 java 脚本变量的值,
#ID- ID of the div in which you want to append this html
#ID- 要在其中附加此 html 的 div 的 ID
example 2: Consider the following HTML:
示例 2:考虑以下 HTML:
<h2>Hello World</h2>
<div class="user">
<div class="inner">Hi</div>
<div class="inner">Bye</div>
</div>
You can create content and insert it into several elements at once:
您可以创建内容并将其一次插入到多个元素中:
$( ".inner" ).append( "<p>GOD IS GREAT</p>" );

