.text()父类

时间:2012-02-20 05:32:03

标签: jquery

我正在尝试将.cartSubPrice文本更改为JSON请求提供的新价格。其他所有东西都能完美地工作,即使总价格变化也是如此,我知道它会因为萤火虫而被退回,只有alert(resultSub)才会显示出来。我只是想弄清楚如何告诉它去正确的地方并改变。任何帮助将不胜感激。

Jquery的

$('.cartUpdate').bind("keyup", function() {
    changeItem = $(this);
    var url = 'cart/update' 
    var qty = $(this).attr('value');
    var rowid = $(this).attr('name');

    if(qty > 0) {
        $.post(url, {qty: qty, rowid: rowid }, function changeCost () {     

            $.getJSON('cart/updatePrice', {rowid: rowid}, function(data) {                  
                //convert to currency                                   
                resultSub = data.subTotal.toFixed(2);
                resultTotal = data.totalPrice.toFixed(2);           

                //change
                $(changeItem).parent('.cartSubPrice').text(resultSub);      
                $('.cartTotalPrice').text(resultTotal);


            });

        });
    }   

    return false;
});

HTML

<div class="cartItem">
    Item 1
    <div class="cartSubPrice">80.00</div>    
    <input type="text" name="76ea881ebe188f1a7e7451a9d7f17ada" value="4" class="cartUpdate" >   
    <a href="#" id="cartDelete" name="76ea881ebe188f1a7e7451a9d7f17ada">x</a>
</div>
<div class="cartItem">
    Item 2
    <div class="cartSubPrice">20.00</div>    
    <input type="text" name="e7a36fadf2410205f0768da1b61156d9" value="1" class="cartUpdate" >   
    <a href="#" id="cartDelete" name="e7a36fadf2410205f0768da1b61156d9">x</a>
</div>

3 个答案:

答案 0 :(得分:1)

尝试更改

$(changeItem).parent('.cartSubPrice').text(resultSub); 

通过

$(changeItem).siblings('.cartSubPrice').text(resultSub);

因为,如果我看一下html,你试图在同一个层次结构中获取一个元素,所以如果你有:

<element></element>
<parent>
      <child></child>
</parent> 

jQuery("child").parent(); //<parent></parent> 
jQuery("parent").siblings(); //[<element></element>] 

此外,正如3nigma建议的那样,如果您只想要与选择器匹配的第一个元素,则可以使用.closest()

答案 1 :(得分:1)

 $(changeItem).closest('.cartSubPrice').html(resultSub);      
 $(changeItem).val(resultTotal);

答案 2 :(得分:1)

类似的东西:

('.cartSubPrice').html(123); OR
('.cartSubPrice:eq(0)').html(123); OR