find is not a function jquery

2019-04-15 22:30发布

good day,

I have my view, where I am trying to render a template

<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> 

And an ajax call

//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);
                })

I used console log to see if the variable clone contains html, and it does.My problem is that I receive a message >>> find is not a function.

What should I do? thanks.

1条回答
再贱就再见
2楼-- · 2019-04-15 23:26

The issue is because clone is a string that contains the HTML of the #template element. It's not a jQuery object. This is why you get the error.

To fix this, you need to reference the cloned content within a jQuery object. You can achieve that by using appendTo() and storing the reference. Something like this:

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);
  });
});
查看更多
登录 后发表回答