以下是我的 html 代码,由 php while 循环生成:
<select class="menu_extra_item">
<option>--Qnt--</option>
<option>1</option>
<option>2</option>
<option>2</option>
</select>
<select class="menu_extra_item"/>
<option>--Qnt--</option>
<option>1</option>
<option>2</option>
<option>2</option>
</select>
<tr class="menu_extra_item_change">
<td>$32</td>
</tr>
<tr class="menu_extra_item_change">
<td>$10</td>
</tr>
我想在选择选项更改时更改值(价格如 32 美元)。
例如
I select (first select) option `1`then it will be show `$32`
I select (first select) option `2`then it will be show `$62`
I select (second select) option `1`then it will be show `$10`
I select (second select) option `2`then it will be show `$20`
为了获得此输出,我使用了以下 jQuery 代码,但它并没有完全按照我想要的方式工作:(
jQuery 代码:
$(".menu_extra_item").each(function() {
$(this).change(function() {
var menu_extra_item =$(this).val();
var menu_extra_item_change = parseInt($('.menu_extra_item_change').text().replace(/[^0-9.]/g, ""));
alert(menu_extra_item_change);
var total_ex_price = menu_extra_item * menu_extra_item_change;
$(".menu_extra_item_change").each(function() {
$(".menu_extra_item_change").text("$"+total_ex_price);
});
});
});
最佳答案
您也可以尝试这个:
var prices = [32,10];
$("body").on("change",".menu_extra_item",function() {
var selInd = $(this).index() - 1;
var newVal = prices[selInd] * $(this).val();
$(".menu_extra_item_change").eq(selInd).text("$" + newVal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select class="menu_extra_item">
<option>--Qnt--</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<select class="menu_extra_item">
<option>--Qnt--</option>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<table>
<tr class="menu_extra_item_change">
<td>$32</td>
</tr>
<tr class="menu_extra_item_change">
<td>$10</td>
</tr>
</table>
关于javascript - 选择选项更改时如何更改值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38218423/