[英]Passing function as parameter to jQuery template
I'm trying to send a function as parameter to a jQuery template and display the first element returned by the function. 我正在尝试将一个函数作为参数发送到jQuery模板,并显示该函数返回的第一个元素。
In the following example, data variable is a function and I'm trying to append first element returned. 在下面的示例中,data变量是一个函数,我试图附加返回的第一个元素。 It's not a solution to store data into a variable because there are many cases when data is an array, not a function. 这不是将数据存储到变量中的解决方案,因为在许多情况下,数据是数组而不是函数。
var template= ' {{each things}}{{if $index == 0}}<span>${this.Name}</span>{{/if}}{{/each}}';
$('.dropdownText').text(jq.tmpl(template, data));
I am not sure if i got the question rigt but if the problem is data can be a function or array you probably just have to do this 我不确定是否有问题,但如果问题是数据可以是函数或数组,则可能只需要这样做
var selectedTemplate = ' {{each things}}{{if $index == 0}}<span>${this.Name}</span>{{/if}}{{/each}}';
function getData(data) {
if (Array.isArray(data)) return data;
if (typeof data === 'function') return data();
}
$('.dropdownText').text(UMT_jq.tmpl(selectedTemplate, getData(data)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.