【问题标题】:jQuery Find not finding element in HTML templatejQuery在HTML模板中找不到元素
【发布时间】:2018-06-05 02:26:13
【问题描述】:

我有一个telerik KendoUI 模板,我将它加载到一个jQuery 对象中。这是有效的。

<script type="text/x-kendo-template" id="customKeywordsEditorPopup">
    Custom Keywords
    <input style="width:100%" id="inpKeywords"/>
</script>

现在这里是 JavaScript 代码,它没有给我预期的结果:

         var popupHtml = $("#customKeywordsEditorPopup"); //This works

         alert($(popupHtml).html()); //This outputs the HTML as expected
         alert($(popupHtml).find('#inpKeywords').length); //This returns 0 instead of 1

不幸的是,$(popupHtml).find('#inpKeywords') 不返回实际元素。它应该引用 INPUT。

知道为什么这不起作用吗?

【问题讨论】:

    标签: javascript jquery telerik


    【解决方案1】:
    $(popupHtml).find('#inpKeywords').length
    

    返回 0,因为您的 &lt;script&gt; 标记中没有元素。 &lt;script&gt; 标签内的文本不会呈现为 html。

    为了让你的模板变成 html,你必须通过 kendo 传递它,将它作为 html 传递给你选择的容器,最后你可以用你的 id 选择器来选择它

    var template = kendo.template($("#customKeywordsEditorPopup").html());
    $("#SomeContainer").html(template({}));
    var input = $("#inpKeywords");
    

    演示

    var templateText = $("#customKeywordsEditorPopup").text();
    
    var template = kendo.template(templateText);
    $("#SomeContainer").html(template({}));
    var input = $("#inpKeywords");
    input.val('Some value');
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://kendo.cdn.telerik.com/2018.2.516/js/kendo.all.min.js"></script>
    <link ref="stylesheet" href="https://kendo.cdn.telerik.com/2018.2.516/styles/kendo.all.min.css">
    
    <script type="text/x-kendo-template" id="customKeywordsEditorPopup">
      Custom Keywords
      <input style="width:100%" id="inpKeywords" />
    </script>
    
    <div id="SomeContainer"></div>

    【讨论】:

      猜你喜欢
      • 2012-01-14
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 2016-10-06
      • 2011-05-22
      • 2016-08-30
      • 1970-01-01
      • 2012-05-16
      相关资源
      最近更新 更多