2014-11-01 84 views
0

使用php foreach得到如下的html。因此id就像价格1,价格2,价格3等。jquery如何获得id的id值(最近的id/id在同一行中)

用户可更改数量。在这种情况下,我必须将价格乘以更改的数量。我决定用jQuery来做。

首先访问quantity

$('[id^="quantity"]').change(function(){ 
var quantity = $(this).val(); 
}); 

但无法获得价格的html值。试图

var price = $(this).find('[id^="price"]').attr('id'); 
var price = $(this).find('div[id^="price"]').html(); 

在这两种情况下,得到了undefined

这里是HTML代码的一部分

<div class="shop_cart_box_around"> 

    <div class="shop_cart_price"> 
    <div class="span_cart_name_txt" id="price1">789</div> 
    </div> 

    <div class="shop_cart_quantity"> 
    <input type="text" name="quantity[]" id="quantity1" value="3"/> 
    </div> 

</div> 

<div class="shop_cart_box_around"> 

    <div class="shop_cart_price"> 
    <div class="span_cart_name_txt" id="price2">54</div> 
    </div> 

    <div class="shop_cart_quantity"> 
    <input type="text" name="quantity[]" id="quantity2" value="1"/> 
    </div> 

</div> 

回答

1

你必须使用closest()获得具有类shop_cart_box_around父元素,然后用find()来得到它的子元素是这样的:

$(this).closest(".shop_cart_box_around").find('[id^="price"]').attr('id'); 

为了得到价格(指价格DIV值)使用text()

$(this).closest(".shop_cart_box_around").find('[id^="price"]').text(); 

$(function(){ 
 

 
    $('[id^="quantity"]').change(function(){ 
 
var quantity = $(this).val(); 
 
    alert("Id : "+ $(this).closest(".shop_cart_box_around").find('[id^="price"]').attr('id')); 
 
alert("Value : " +$(this).closest(".shop_cart_box_around").find('[id^="price"]').text()); 
 
}); 
 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> 
 
<div class="shop_cart_box_around"> 
 

 
    <div class="shop_cart_price"> 
 
    <div class="span_cart_name_txt" id="price1">789</div> 
 
    </div> 
 

 
    <div class="shop_cart_quantity"> 
 
    <input type="text" name="quantity[]" id="quantity1" value="3"/> 
 
    </div> 
 

 
</div> 
 

 
<div class="shop_cart_box_around"> 
 

 
    <div class="shop_cart_price"> 
 
    <div class="span_cart_name_txt" id="price2">54</div> 
 
    </div> 
 

 
    <div class="shop_cart_quantity"> 
 
    <input type="text" name="quantity[]" id="quantity2" value="1"/> 
 
    </div> 
 

 
</div>

+1

这应该得到的价格div的ID,但它不会得到的价格。 – j08691 2014-11-01 18:23:14

+0

var price = $(this).closest(“。shop_cart_box_around”)。find('[id^=“price”]').html();这工作。谢谢! – user2118559 2014-11-01 18:25:06

+0

使用'val()'而不是'html()'输入元素 – 2014-11-01 18:26:44