简体   繁体   English

jQuery parents() 选择器失败

[英]jQuery parents() selector failing

I have an anchor, and I have attached an onClick callback to it, so once it is clicked, an AJAX request is fired which calls a view that deletes the image from the database.我有一个锚点,并且我已经附加了一个 onClick 回调给它,所以一旦它被点击,就会触发一个 AJAX 请求,该请求调用一个从数据库中删除图像的视图。 It should also remove <div class="image-preview"> altogether, too, however that is not happening for some reason.它也应该完全删除<div class="image-preview"> ,但是由于某种原因这没有发生。

When I tested div removal code in JSFiddle , it works.当我在JSFiddle测试 div 删除代码时,它可以工作。 The image is successfully getting removed from the database and delete_view is involved in the process.图像已成功从数据库中删除,并且 delete_view 参与了该过程。 I have also tried to console.log from inside the success callback and I can see a debug message.我还尝试从成功回调内部进行console.log ,我可以看到一条调试消息。 console.log($(this).parents('.image-preview')); returns Object { length: 0, prevObject: Object(1) } , thus I think the selector is failing.返回Object { length: 0, prevObject: Object(1) } ,因此我认为选择器失败了。

What could be the reason?可能是什么原因?

HTML: HTML:

<div id="information">
  <div class="image-previews">
    <div class="image-preview">
      <img src="/media/tmp/None/IMG_20190507_144128.jpg" width="80" height="54">
      <p><a id="115" class="delete-temp-image-link">delete</a></p>
      <label><input type="radio" name="main" value="IMG_20190507_144128.jpg">main</label>
    </div>
  </div>
  <div id="div0">
    <div>Name: IMG_20190507_144128.jpg</div>
    <div>Size: 3.03MB</div>
    <div>Type: image/jpeg</div>
    <div class="progressNumber">100%</div>
  </div>
</div>

jQuery: jQuery:

var $deleteClicked = function(event) {
  var url = Urls.deleteTempImage(event.target.id);

  $.ajax({
    url: url,
    data: {
      'id': event.target.id
    },
    success: function (data) {
      console.log('spam');
      $(this).parents('.image-preview').remove();
    }
  });      
}        

$(document).on('click', '.delete-temp-image-link', $deleteClicked);

view:看法:

def delete_view(request, id):
    img = get_object_or_404(TemporaryImage, id=id)
    img.delete()
    return HttpResponse('successfull')

You have to store $(this) before run $.ajax because you are using it in a wrong context.您必须在运行$.ajax之前存储$(this)因为您在错误的上下文中使用它。

var $deleteClicked = function(event) {
var url = Urls.deleteTempImage(event.target.id);
var storedThis = $(this);

    $.ajax({
        url: url,
        data: {
            'id': event.target.id
        },
        success: function (data) {
            console.log('spam');
            storedThis.parents('.image-preview').remove();
        }
    });      
}        

$(document).on('click', '.delete-temp-image-link', $deleteClicked);

This should work as expected.这应该按预期工作。

$(this) isn't available to your named click callback function. $(this)不适用于您的命名点击回调 function。 One way to make your code more explicit would be to store $(this) , as others have said - or, simply use the id that you're already passing anyway.使您的代码更明确的一种方法是存储$(this) ,正如其他人所说 - 或者,只需使用您已经传递的id For example:例如:

var $deleteClicked = function(event) {
  var url = Urls.deleteTempImage(event.target.id);

  $.ajax({
    url: url,
    data: {
      'id': event.target.id
    },
    success: function (data) {
      console.log('spam');
      $("#"+event.target.id).closest('.image-preview').remove();
    }
  });      
}        

$(document).on('click', '.delete-temp-image-link', $deleteClicked);

Also, note that I used jQuery .closest() instead of .parents() .另外,请注意我使用了 jQuery .closest()而不是.parents() From the jQuery docs , .closest() does the following:jQuery 文档中, .closest()执行以下操作:

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.对于集合中的每个元素,通过测试元素本身并向上遍历其在 DOM 树中的祖先来获取与选择器匹配的第一个元素。

Check out the docs page for a description of the differences between .closest() and .parents() .查看文档页面,了解.closest().parents()之间的区别。 The main difference is that .closest() only traverses up the DOM tree until it finds a match, rather than traversing all the way up to the root element.主要区别在于.closest()仅向上遍历 DOM 树直到找到匹配项,而不是一直遍历到根元素。 I doubt there are huge performance implications, but since you're selecting only one <div> , it's slightly more precise code.我怀疑这会对性能产生巨大影响,但由于您只选择了一个<div> ,因此它的代码更精确一些。

Try this code for jQuery.试试这个 jQuery 的代码。

var $deleteClicked = function(event) {
  var url = Urls.deleteTempImage($(this).attr('id'));

  $.ajax({
    url: url,
    data: {
      'id': $(this).attr('id')
    },
    success: function (data) {
      console.log('spam');
      $(this).parents('.image-preview').remove();
    }
  });      
}        

$('.delete-temp-image-link').on('click', $deleteClicked);

Same problem occur to me as well.我也遇到同样的问题。 Actually '$(this)' is tricky as it may seem.实际上,'$(this)' 看起来很棘手。

'$(this)' cannot be used in success function as it lost it scope in success function. '$(this)' 不能成功使用 function,因为它丢失了 scope 成功 function。 Try to define '$(this)' outside the success(ie, before ajax),eg尝试在成功之外定义'$(this)'(即在ajax之前),例如

const element = $(this)常量元素 = $(这个)

And then in your success function:然后在您的成功 function 中:

element.parents('.image-preview').remove(); element.parents('.image-preview').remove();

This should definitely solve your problem.这绝对可以解决您的问题。

Hope this helps!希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM