gpt4 book ai didi

jquery - 通过 jquery-tmpl 中的函数调用附加动态 HTML 元素

转载 作者:行者123 更新时间:2023-12-01 04:29:28 27 4
gpt4 key购买 nike

我正在使用jquery-tmpl模板库构建动态<select>列表。在我的模板中,我有一个返回所有 <option> 的函数调用。现有 <select> 中的元素页面上的元素。

在我的模板中,函数调用成功执行并返回 .html()从现有的<select>列表,但将其呈现为 DOM 中的文本,而不是将 HTML 附加到 <select>列表。

我知道我的函数仅返回一个字符串,并且看起来被如此对待,但我不知道如何实际获取对 <select> 的引用模板中的元素来执行任何 jQuery 功能。

如何附加 <option>列出模板 HTML 元素,或获取对模板元素的引用?

这是我的模板:

<script id="searchTemplate" type="text/x-jquery-tmpl">
<select id="destinations" class="destinations">
${getDestinationList()}
</select>
</script>

我的函数返回 <option>作为字符串的集合:

function getDestinationList(){
return $("#tabs-0 select[id$='destinations']").html(); //returns HTML list as string successfully
}

提前致谢!!

最佳答案

好的,明白了,抱歉。花了几个小时试图解决这个问题,并在发布后几分钟找到了解决方案(打脸)。

我找到的解决方案是使用插件的编译模板功能。我之前曾使用 $.template( "#destinationList", getDestinationList() ); 尝试过此操作,并且在浏览器中遇到脚本错误。结果我使用的是旧版本的插件,并且该函数实际上具有签名 $.templates(name, tmpl)。然后我检查是否拥有最新版本,发现签名已更改为与当前文档一致的 $.template(name, tmpl) 。不确定什么时候改变,但是......

在弄清楚这一点之后,我能够正确地使用编译的模板功能,如下所示:

<script id="searchTemplate" type="text/x-jquery-tmpl">
<select id="destinations" class="destinations">
{{tmpl "#destinationList"}}
</select>
</script>

并在页面加载中定义编译模板,如下所示:

$(function(){
$.template( "#destinationList", getDestinationList() );
});

使用我未更改的功能:

function getDestinationList(){
return $("#tabs-0 select[id$='destinations']").html();
}

向任何研究此问题的人致歉,但希望这对其他人有帮助。

关于jquery - 通过 jquery-tmpl 中的函数调用附加动态 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3764409/

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