2014-11-01 52 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

相關問題