gpt4 book ai didi

javascript - 动态加载 jQuery 模板

转载 作者:搜寻专家 更新时间:2023-11-01 04:11:36 26 4
gpt4 key购买 nike

对于 jQuery 模板:

http://api.jquery.com/category/plugins/templates/

我希望能够从服务器动态加载模板,而不是在页面上预先定义它。

我在项目中看到的演示都使用预定义的模板。经过一些研究,我发现这是可能的。

我尝试这样做但它不起作用:

<script src="child.html" type="text/x-jquery-tmpl"></script>

我试过这样做,但没有用:

$(function () {
$.get("child.html", function (data) {
//Add template
$.template("tmplChild", data);
});

//template binds before async call is done
$.tmpl("tmplChild").appendTo("body");
});

最后,我将其归结为以下 hack:

so.html(这是主页):

<html>
<head>
<title></title>
</head>
<body>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.js"></script>

<script type="text/javascript" src="so.js"></script>

<script type="text/javascript">

$(function () {
initTemplates(templateReady);
});

function templateReady() {
$.tmpl("tmplChild").appendTo("body");
}

</script>
</body>
</html>

child.html(这是子模板)

<h1>Child Loaded</h1>

so.js(这是我用于 ajax 加载 js 模板的 hack)

function initTemplates(callback) {
var templateUrl = "child.html";
var templateName = "tmplChild";

initTemplate(templateUrl, templateName, callback);
}

function initTemplate(url, name, callback) {
var opts =
{
type: "GET",
url: url,
dataType: ($.browser.msie) ? "text" : "xml",
success: function (data) {
xmlCallback(data, name, callback);
},
error: function (x) {
xmlCallback(x.responseText, name, callback);
}
}

$.ajax(opts);
}

function xmlCallback(data, name, callback) {

if (typeof data != "string") {
if (window.ActiveXObject) {
var str = data.xml;
data = str;
}
// code for Mozilla, Firefox, Opera, etc.
else {
var str = (new XMLSerializer()).serializeToString(data);
data = str;
}
}

//only takes strings!
$.template(name, data);

callback();
}

这就是我不喜欢它的地方。

  1. 这不适用于 Chrome
  2. 加载一些模板似乎有很多代码
  3. 我失去了使用 $(document).ready() 的能力。我现在必须将我的所有代码都放在这个 templateReady() 方法中,以确保“模板安全”。

有解决办法吗?

谢谢,

最佳答案

只需将模板正文加载为简单文本,而无需将其放入虚拟 <script>堵塞。您可以使用 $.tmpl(body, params)填充模板并将其转换为字符串以附加到 DOM。

“不是真正的脚本”的整个事情<script> block 只是在某些情况下有用的便利。

编辑 — 示例:

$.get("/some/url/for/a/template", function(templateBody) {
var expandedTemplate = $.tmpl(templateBody, { param1: 0, param2: "Hello World" });
});

关于javascript - 动态加载 jQuery 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4072698/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com