问题:如何从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还指出,你可能要更换,
用.
这样的价值被正确解析浮动。您可以使用.replace(',', '.')
简单的替换$( this ).text()
代码来实现:
$(".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以及更多此类解决方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句