为什么jQuery parent()找不到我的元素?

Chu*_*utt 0 jquery parent-child jquery-selectors

我只是不能让这个(非常简单)的功能正常工作,parent()似乎没有找到我想要的div并淡出它:(

$('.deleteButton').click( function() {

    var img = $(this).attr('href');
    img = "../"+img;

    var answer = confirm('Are you sure you want to delete this item? (This cannot be undone!)');
    if (answer) {

        $.ajax({
            url: 'scripts/deletePhoto.php',
            data: 'img='+img,
            type: 'POST',
            mode: 'abort',
            success: function(){
                $(this).parents("div.photo").fadeOut('fast');
            }
        });
    }
return false;
});
Run Code Online (Sandbox Code Playgroud)

HTML

<div class="photo">
    <img alt="" src="../static/images/photos/tmp/1.jpg">
    <div class="overlay" style="opacity: 0;">
        <p class="process success message">
            <a href="process_photo.php?img=../static/images/photos/tmp/1.jpg">Process this photo</a>
        </p>
        <p class="delete error message">
            <a href="../static/images/photos/tmp/1.jpg" class="deleteButton">Delete image</a></p>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

我试过$(this).parents(".photo").fadeOut('fast');$(this).cloest("div.photo").fadeOut('fast');,但没有什么是连接:(

Jam*_*iec 6

这是一个范围问题.在successajax 的回调中,this并没有引用你的想法 - 它直接指向函数本身.

您应该缓存$(this)ajax调用之外的副本,并使用:

$('.deleteButton').click( function() {
   var $img = $(this);

   //....//

   $.ajax({
        url: 'scripts/deletePhoto.php',
        data: 'img='+img,
        type: 'POST',
        mode: 'abort',
        success: function(){
            $img.parents("div.photo").fadeOut('fast');
        }
    });

   // ... //
}
Run Code Online (Sandbox Code Playgroud)