[英]How to extract an element from id?
問題:如何從id中提取元素?
HTML:
<div class="product">
<p id="price1">99,00</p>
</div>
<div class="product">
<p id="price2">101,00</p>
</div>
<div class="product">
<p id="price3">50,00</p>
</div>
<div class="product">
<p id="price4">1,99</p>
</div>
<div class="product">
<p id="price5">2,01</p>
</div>
JS:
var sumPrice = 0;
$(".product").click(function() {
if ( i = 1) sumPrice += parseFloat($( "#price" + i ).text())
else if ( i = 2) sumPrice += parseFloat($( "#price" + i ).text())
else if ( i = 3) sumPrice += parseFloat($( "#price" + i ).text())
else if ( i = 4) sumPrice += parseFloat($( "#price" + i ).text())
else if ( i = 5) sumPrice += parseFloat($( "#price" + i ).text())
$(".total").val(sumPrice);
});
我試圖獲得不同的價格並進行總結。 現在,我僅添加第一個值。
怎么樣:
$(".product").click(function() {
sumPrice += parseFloat($( this ).text())
$(".total").val(sumPrice);
});
工作中的JsFiddle 。
作為@bilyonecan還指出,你可能要更換,
用.
這樣就可以正確解析該值以使其浮動。 您可以在$( this ).text()
上使用.replace(',', '.')
進行簡單替換,以編寫代碼:
$(".product").click(function() {
sumPrice += parseFloat($( this ).text().replace(',', '.'))
$(".total").val(sumPrice);
});
如果您真的想找出被點擊項目的id
,可以使用以下方法:
this.id; //gives the id of the clicked element. (javascript style)
$(this).prop('id') //or jQuery style (id of clicked element)
$(this).children().first().prop('id'); //gives the id of the first child element (<p> in your case)
$this
在jQuery / Javascript中 對象$this
是函數或偵聽器所屬的對象,在您的情況下,它是被單擊並具有此單擊處理程序的對象。 $this
非常方便,並且以這種方式使用,這樣您就不需要帶有計數器的ID和更多此類解決方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.