jQuery父元素更改内部HTML

3
我已经有了这个:
$('.event-tools a').click(function() 
{
    var status = $(this).attr('id');
    var id = $(this).parent().attr('id');

    $.ajax({
        type: "GET",
        url: "http://localhost:8888/update/test.php",
        data: "rsvp=" + status + '&id=' + id,
        success: function()
        {
            $(this).parent().html(status);
            //alert(status);
        },
        error: function()
        {
            alert('failz');
        }
    });
});

有了这个:

<span class="rsvp" id="1">
    <a href="#" class="rsvp" id="Attending">Attending</a>
    <a href="#" class="rsvp" id="Maybe Attending">Maybe Attending</a>
    <a href="#" class="rsvp" id="Not Attending">Not Attending</a>
</span>

当我点击其中一个并使用alert()时,它会弹出警告框,但是当我在success:事件中使用$(this).parent().html(status);时,它不会用status更改HTML...


1
我认为你的ID不是有效的ID... - Matti Virkkunen
2个回答

2

success-function 中的 this 与外部不具有相同的作用域,因为 JavaScript 具有函数作用域。您需要执行以下操作以保留外部函数的原始值:

var self = this;
$.ajax({
    // ...
    success: function() {
        $(self).parent().html(status);
    }
});

或者,您可以使用jQuery的.proxy()方法

$.ajax({
    // ...
    success: $.proxy(function() {
        $(this).parent().html(status);
    }, this)
});

现在为什么我没想到这个,代理工作得很好。感谢!(还有5分钟就能接受答案了)。 - MacMac

0

试一下这个

JS:

$('.event-tools a').click(function(ev) 
{
    ev.stopPropagation()

    var status = $(this).attr('id'),
        id = $(this).parent().attr('id'),
        myparent = $(this).parent();

    $.ajax({
        type: "GET",
        url: "http://localhost:8888/update/test.php",
        data: "rsvp=" + status + '&id=' + id,
        success: function()
        {
            $(myparent).parent().html(status);
            //alert(status);
        },
        error: function()
        {
            alert('failz');
        }
    });
    return false;
});

HTML:

<span class="event-tools" id="1"><!-- this has class = "rsvp" -->
    <a href="#" class="rsvp" id="Attending">Attending</a>
    <a href="#" class="rsvp" id="Maybe Attending">Maybe Attending</a>
    <a href="#" class="rsvp" id="Not Attending">Not Attending</a>
</span>

不,它不会改变内部HTML。 - MacMac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接