jquery在父div之外找到下一课

时间:2016-03-02 23:41:06

标签: jquery html

您好我正在尝试在父div之外找到下一个pret_prod_cos类,并且由于某种原因它无效。当我按change课程时,我想将新的html添加到课程pret_prod_cos。这是我的HTML:

<div class="col-sm-5">
   <div class="cart_quantity_button">
                                    <div id="<?php echo $cart['ID_Produs']; ?>" class="input-group input-group-option quantity-wrapper">

                                <span class="input-group-addon input-group-addon-remove quantity-remove btn">
                                    <span class="glyphicon glyphicon-minus"></span>
                                </span>

                               <input class="cart_quantity_input quantity-count" type="text" name="quantity" id="<?php echo $cart['ID_Produs']; ?>inp" value="<?php echo $cart['qty']; ?>" autocomplete="off" size="2">

                                <span class="input-group-addon input-group-addon-remove quantity-add btn">
                                    <span class="glyphicon glyphicon-plus"></span>
                                </span>

                            </div>
   </div>
                                <div class="mod" style="display:none;"> 
                                <a class="change" href="/engine/shop/edit_cos.php?id=<?php echo $cart['ID_Cos']; ?>  " data-pret="<?php echo $cart['Pret']; ?>">modifică</a>
                                </div>
</div>

<div class="col-sm-2">
<h2 class="pret_prod_cos"><?php echo $cart['pret']; ?> lei</h2>
<a href="engine/shop/sterge_prod.php?id=<?php echo $cart['ID_Cos']; ?>">elimina din cos</a>
</div>

jquery的

<script type="text/javascript">
$(".change").click(function(e){

    e.preventDefault();
    var pret=$(this).data("pret");
   var qty = $(this).parents().eq(1).find('input').val();
   var total=parseInt(pret)*parseInt(qty);
    var href = $(this).attr('href');

   $.ajax({
      type: "POST",
    url: href,
    data: { qtyy:qty },
    success: function(result) {
        $(this).parent().closest(".col-sm-2").find(".pret_prod_cos").html(total);
       cos();
    }
});

});
</script>

1 个答案:

答案 0 :(得分:1)

.closest()就像parent()一样。由于.col-sm-2不是.change的父级,因此表达式不起作用。您需要导航到.col-sm-5的父.change,然后使用.next()获取具有指定类的下一个发生元素。此外,您需要将对当前对象(this)的引用定义为在ajax完成之后使用的变量,因为在ajax之后,您将松散引用&#39; this&#39;对象

$(".change").click(function(e){

    e.preventDefault();
    var pret=$(this).data("pret");
   var qty = $(this).parents().eq(1).find('input').val();
   var total=parseInt(pret)*parseInt(qty);
    var href = $(this).attr('href');
    var $this = $(this);
    $.ajax({
      type: "POST",
      url: href,
      data: { qtyy:qty },
      success: function(result) {
       $this.closest(".col-sm-5").next('.col-sm-2').find(".pret_prod_cos").html("total"); 
      cos();
      }
   });
 });