无法使用jquery ajax成功回调函数遍历dom [英] unable to traverse up the dom using jquery ajax success callback function

查看:55
本文介绍了无法使用jquery ajax成功回调函数遍历dom的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的html中,我试图使用$(this)遍历DOM,但是我找不到一些问题.

In the below html i am trying to traverse up the DOM using $(this) but some problem i am unable to find.

<div class="albumWrapper">
    <div class="album" id="test1">
        <div class="fadein">
            <img src="images/album/1_b.jpg" />
            <img src="images/album/2_b.jpg" />
        </div>
        <div class="descWrapper">
            <h1>
                <a href="1">Weddings</a>
            </h1>
            <div class="description">
                <span class="quotes">"</span>description 1<span class="quotes">"</span>
            </div>
        </div>
    </div>
    <div class="gallery"></div>
    <div class="album" id="test1">
        <div class="fadein">
            <img src="images/album/1_b.jpg" />
            <img src="images/album/2_b.jpg" />
        </div>
        <div class="descWrapper">
            <h1>
                <a href="2">Weddings</a>
            </h1>
            <div class="description">
                <span class="quotes">"</span>description 2<span class="quotes">"</span>
            </div>
        </div>
    </div>
    <div class="gallery"></div>
</div>

这是我写的jQuery.但是当我使用$(this)时似乎有一些问题. 因此,请有人帮助我找到错误.会很有帮助.

This is jquery I have written. But itseems to have some problem when i am using $(this). So please someone help me find the mistake. It would be helpful.

        $(".descWrapper h1 a ").on("click", function(e) {
            e.preventDefault();
            $.ajax({
                url: 'ajaxify/gallery.php',
                type: "get",
                data: "id=" + $(this).attr('href'),
                beforeSend: function() {

                },
                success: function(data) {
                    $(this).parents(".album").next(".gallery").html(data);
                },
                error: function(xhr, status, errorThrown) {
                    alert();
                }
            });
        });

推荐答案

使用ajax的上下文选项:

Use context option of ajax:

$(".descWrapper h1 a ").on("click", function (e) {
    e.preventDefault();
    $.ajax({
        context:this,
        url: 'ajaxify/gallery.php',
        type: "get",
        data: "id=" + $(this).attr('href'),
        beforeSend: function () {

        },
        success: function (data) {
            //now 'this' here refers to the clicked link
            $(this).parents(".album").next(".gallery").html(data);
        },
        error: function (xhr, status, errorThrown) {
            alert();
        }
    });
});

这篇关于无法使用jquery ajax成功回调函数遍历dom的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆