查找不是函数 jquery

find is not a function jquery

美好的一天,

我有我的观点,我正在尝试渲染模板

<div id="template" style="display:none;">
<div class="col-lg-4 col-md-6 col-sm-12">
    <div class="thumbnail">
        <a href="" class="btn btn-primary btn-sm editar">Editar</a>
        <h3 class="centrar"></h3>
        <a class="index" href="">
            <img class="image" src="" /> 
        </a>
        <p class="description">data[i].Descripcion</p>
    </div>
</div> 

还有一个 ajax 电话

//ajax starts here...
//....
success: function (data) {
                $.each(data, function (index, item) {
                    var clone = $('#template').clone().html();
                    console.log(clone);
                    parent.append(clone);
                    clone.find('.editar').attr('href', editarUrl + '/' + item.Id);
                    clone.find('.centrar').text(item.Titulo);
                    clone.find('.index').attr('href', indexUrl + '?CursoId' + item.Id);
                    clone.find('.image').attr('src', item.ImagenUrl);
                    clone.find('.description').text(item.Descripcion);
                })

我使用控制台日志查看变量 clone 是否包含 html,它 does.My 问题是我收到一条消息 >>> find is not a function.

我该怎么办?谢谢。

问题是因为 clone 是一个包含 #template 元素的 HTML 的字符串。它不是 jQuery 对象。这就是您收到错误的原因。

要解决此问题,您需要在 jQuery 对象中引用克隆的内容。您可以通过使用 appendTo() 并存储引用来实现。像这样:

success: function (data) {
  $.each(data, function (index, item) {
    var html = $('#template').html();
    var $clone = $(html).appendTo(parent);
    $clone.find('.editar').attr('href', editarUrl + '/' + item.Id);
    $clone.find('.centrar').text(item.Titulo);
    $clone.find('.index').attr('href', indexUrl + '?CursoId' + item.Id);
    $clone.find('.image').attr('src', item.ImagenUrl);
    $clone.find('.description').text(item.Descripcion);
  });
});