【问题标题】:Append dynamic HTML elements through function call in jquery-tmpl通过 jquery-tmpl 中的函数调用附加动态 HTML 元素
【发布时间】:2011-04-15 10:21:34
【问题描述】:

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

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

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

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

这是我的模板:

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

我的函数将&lt;option&gt; 集合作为字符串返回:

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

提前致谢!!

【问题讨论】:

    标签: jquery templates jquery-templates


    【解决方案1】:

    好的,知道了,对不起。花了几个小时试图解决这个问题,并在发布后几分钟找到了解决方案(打脸)。

    我找到的解决方案是使用插件的编译模板功能。我之前使用$.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();
    }
    

    向任何对此进行调查的人表示歉意,但希望这会对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-01-11
      • 2014-03-11
      • 1970-01-01
      • 2022-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-01
      • 1970-01-01
      相关资源
      最近更新 更多