【问题标题】:jQuery Parent change inner HTMLjQuery Parent 更改内部 HTML
【发布时间】:2010-09-23 21:42:14
【问题描述】:

到目前为止我得到了这个:

$('.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); 时,它不会使用@ 更改HTML 987654326@...

【问题讨论】:

  • 我认为你的身份证不是有效身份证...

标签: jquery parent innerhtml


【解决方案1】:

this 在您的成功函数内部与外部的范围不同,因为 JavaScript 具有函数范围。你需要做这样的事情来保留外部函数this的原始值:

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

或者,您可以使用 jQuery 的 .proxy()-method:

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

【讨论】:

  • 现在我为什么没想到,代理工作得很棒。为此干杯! (直到我可以接受答案还有 5 分钟)。
【解决方案2】:

试试这个

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。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-19
  • 2014-09-04
相关资源
最近更新 更多