有没有可以用来提供 HTML 内容的 JavaScript 库?我想创建一个内容可以动态更改的DIV。
<div id="header">
<h2>Header here</h2>
</div>
<div id="dynamic-content">
<p>-- Dynamic content here --</p>
</div>
<div id="footer">
<h3>Footer</h3>
</div>
我计划为此使用 jQuery,只需从服务器检索 HTML 标记,然后使用 jQuery 的 html()
函数替换 #dynamic-content
的内容。我只是好奇如果检索到的 HTML 标记“很大”(比如说整篇文章),这是否实用。
是否有一个简单的 JavaScript 模板框架可以实现这一点?或者我什至可以使用模板 JS 框架吗?
最佳答案
--助手--
var uiHelper = function () {
var htmls = {};
var getHTML = function (options) {
/// <summary>Returns HTML in a string format</summary>
/// <param name="options" type="object">options{url:The url to the file with the HTML,successCallback:function,errorCallback:function,isAsync:true||false,cache:true|false}</param>
function xhrSuccess() {
if (this.cache) { htmls[this.url] = this.responseText; };
if (this.successCallback) {
this.successCallback.apply(this.responseText, this.arguments);
} else {
return htmls[this.url];
};
};
function xhrError() {
if (this.errorCallback) {
this.errorCallback.apply(this.statusText);
} else {
return this.statusText;
};
};
if (!htmls[options.url]) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", options.url, options.isAsync);
xmlhttp.cache = options.cache || false;
xmlhttp.url = options.url;
xmlhttp.onload = xhrSuccess;
xmlhttp.onerror = xhrError;
xmlhttp.successCallback = options.successCallback || undefined;
xmlhttp.errorCallback = options.errorCallback || undefined;
xmlhttp.send();
} else {
if (options.successCallback) {
options.successCallback.apply(htmls[options.url], this.arguments);
} else {
return htmls[options.url];
};
};
};
return {
getHTML: getHTML
};
}();
--用法---
uiHelper.getHTML({
url: url, isAsync: true, cache: false, successCallback: function () {
document.getElementById('dynamicContent').innerHTML = this;
}
});
--您的 HTML---
<div id="header">
<h2>Header here</h2>
</div>
<div id="dynamic-content">
<p id='dynamicContent'>-- Dynamic content here --</p>
</div>
<div id="footer">
<h3>Footer</h3>
</div>
关于javascript - 网站动态内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21896700/