jQuery:在Ajax调用之后更改元素值

时间:2013-05-07 21:19:41

标签: php jquery

我正在尝试在使用jQuery.ajax之后更改span的值。

的JavaScript

$(document).on('click', '.kssico', function(event) {
    var for_uid = $(this).parents("li").attr('data'),
        for_name = $(this).parents("li").attr('unme'),
        dataString = "for_uid=" + for_uid + "&for_name=" + for_name; 

    $.ajax({
        type: "POST",
        url: "include/ajax.php",
        data: dataString,
        success: function (html) {
            if(html=="300") {
                $('#myModal .modal-body p').html("Error Please Try Again.");
                $('#myModal').modal('show');
            }
            else {
                $(this).parents("li span.mi-val").html(html);
                $('#myModal .modal-body p').html("The Requested Action Has Been Notified To Your Friend.");
                $('#myModal').modal('show');
            }
        }
    });
});

HTML

<li class="mispan main-span" >
    <div class="thumbnail">
        <h3 class="miheader">Dewashree Singh</h3>
        <a >
            <div class="miprofile-pic-cnt" ></div>
        </a>
        <div class="caption">
            <p>
                <a href="#" class="btn kssico miclickks">
                    <img src="/lisps.png"><span class="mi-val">0</span>
                </a>
                <a href="#" class="btn bdico miclickbd">
                    <img src="/besd.png"><span class="mi-val">1</span>
                </a>
            </p>
        </div>
    </div>
</li>

当我点击a.miclickks时,它应该完成Ajax调用并返回一个值也放在按钮锚点的span中。但是,没有任何改变!

jsFiddle

2 个答案:

答案 0 :(得分:1)

我不知道你的整个代码是什么样的,但你应该能够修改它来做你想做的事情:

$('#id').on('click', function() {
    var that = this;
    $.ajax({
        url: 'wherever.php',
        success: function(html) {
          $(that).find("li span.mi-val").html(html);
        }
    });

答案 1 :(得分:0)

看起来你有两个问题。第一个是@Barmar上面发布的,mi-val是micclickks的孩子,而不是父母。第二个是你的ajax完成函数是异步的,所以$(this)不是你预期的那样。但这两个都是可以解决的。

你的代码有点乱,你的html缺少正确的属性,但这是我认为你想要的大致:

$('.kssico').on('click', function(event) {

     var for_uid = $(this).parents("li").attr('data'); //the li element in your html doesn't have a data attribute
     var for_name = $(this).parents("li").attr('unme'); //the li element in your html doesn't have a 'unme' attribute
     var dataString = "for_uid=" + for_uid + "&for_name=" + for_name; 

$.ajax({
    type: "POST",
    context: this,
    url: "include/ajax.php",
    data: dataString,
    success: function (html) {
        if(html=="300")
        {
            $('#myModal .modal-body p').html("Error Please Try Again.");
            $('#myModal').modal('show');
         }
        else
        {
            $(this).parents("li span.mi-val").html(html);
            $('#myModal .modal-body p').html("The Requested Action Has Been Notified To Your Friend.");
            $('#myModal').modal('show');
        }
    }
    });
});