如何使用 java 脚本通过更改用户购物篮中的产品数量来更改总价

我想在更改数量时更改总价。这是视图:


@foreach (var item in Model)

                    {

                        <tr>

                            <td>@item.Product.Name</td>

                            <td><input type="number" value="@item.Count" id="Count" /></td>

                            <td id="Price">@item.Product.Price</td>

                            <td id="SumPrice">@item.SumPrice</td>

                       </tr>

                    }

这是我使用的java脚本,但它不起作用。当我更改数量时,总价不会更改。


 $('#Count').on('keyup',function(){

    var tot = $('#Price').val() * this.value;

    $('#SumPrice').val(tot);

});


当年话下
浏览 79回答 1
1回答

摇曳的蔷薇

您不能对ids多个元素使用相同的内容,而是使用类。然后,使用$(this).closest("tr")获取最接近的tr参考并使用来获取您需要计算.find的值。td演示代码:$('.Count').on('keyup change', function() {&nbsp; //get closest tr -> find price class get value&nbsp; var tot = $(this).closest("tr").find('.Price').text() * this.value;&nbsp; $(this).closest("tr").find('.SumPrice').text(tot); //set value});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><table>&nbsp; <tr>&nbsp; &nbsp; <td>Abc</td>&nbsp; &nbsp; <!--added class-->&nbsp; &nbsp; <td><input type="number" value="1" class="Count" /></td>&nbsp; &nbsp; <td class="Price">21</td>&nbsp; &nbsp; <td class="SumPrice">21</td>&nbsp; </tr>&nbsp; <tr>&nbsp; &nbsp; <td>Xyz</td>&nbsp; &nbsp; <td><input type="number" value="1" class="Count" /></td>&nbsp; &nbsp; <td class="Price">12</td>&nbsp; &nbsp; <td class="SumPrice">12</td>&nbsp; </tr></table>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript