gpt4 book ai didi

jquery - 如何在我的插件之外创建可用的递归 jQuery 模板 (tmpl)?

转载 作者:行者123 更新时间:2023-12-01 06:06:19 24 4
gpt4 key购买 nike

我有一个 Json 对象,我正在将其转储到 jQuery 模板 (tmpl) 中。它需要递归,因为 Json 对象可以是 n 层深。这段代码有效。但是,如果我将它包装在一个函数中(它属于我正在编写的 jQuery 插件),它就会停止工作。要明白我的意思,只需取消 Javascript 中函数包装器的注释即可。

玩一下:http://jsfiddle.net/dbme/tkdZg/6/

HTML:

<script id="evntTemplate" type="text/x-jquery-tmpl">

{{if data.identifiers}}
<div id="${data.identifiers.id}" class="bsa-event">
type: ${data.identifiers.type}<br />
id: ${data.identifiers.id}<br />
{{if children}}
{{each(i, child) children}}
<blockquote>
<p>
{{if children}}
{{tmpl(children) "evntTemplate"}}
{{/if}}
</p>
</blockquote>
{{/each}}
{{/if}}
</div>
{{/if}}
</script>
<div id="eventList"></div>

Javascript:

//(function ($) {
// $.fn.SomePlugin = function() {
var movies = {
"data": {
"identifiers":{
"type":0, "id":"makeunique_907827h"
}
},
"children": {
"data": {
"identifiers": {
"type":1, "id":"makeunique_716786g"
}
},
"children": {
"data": {
"identifiers": {
"type":1, "id":"makeunique_234355g"
}
}
}
}
};

/* Render the template with the data */
var evntTemplate = $( "#evntTemplate" ).template( "evntTemplate" );
$.tmpl(evntTemplate, movies).appendTo("#eventList");
//};
//}( jQuery ));

更多信息:我正在使用 RequireJS 加载文件并启动整个过程。我认为这就是扼杀范围的原因。这是代码:

require(["jquery", "jquery.tmpl", "jquery.someplugin"], function($) {
$(function() {
$('body').SomePlugin();
});
});

最佳答案

这是因为您没有将 jquery 对象作为参数传递给函数包装器。

工作示例:http://jsfiddle.net/tkdZg/3

将其更改为:

(function($) {
var movies = {
"data": {
"identifiers":{
"type":0, "id":"makeunique_907827h"
}
},
"children": {
"data": {
"identifiers": {
"type":1, "id":"makeunique_716786g"
}
},
"children": {
"data": {
"identifiers": {
"type":1, "id":"makeunique_234355g"
}
}
}
}
};

/* Render the template with the data */
var evntTemplate = $( "#evntTemplate" ).template( "evntTemplate" );
$.tmpl(evntTemplate, movies).appendTo("#eventList");
})($); //########################

关于jquery - 如何在我的插件之外创建可用的递归 jQuery 模板 (tmpl)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5653578/

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