javascript - 选择选项更改时如何更改值?

标签 javascript jquery

以下是我的 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/

相关文章:

php - jQuery .html() 在 IE8 中不工作

jquery - 循环中 chrome.tabs.create 的错误

javascript - 使用 jQuery 动态元素

javascript - 检测在 javascript 中删除的 DOM 项目

javascript - Google Maps 或 Cesium 在 map 上渲染动态几何图形

javascript - 使最喜爱的按钮显示标记,无需重新加载页面 Ionic

javascript - 更改不使用 id 的标签的类

javascript - 火狐 WebExtension API : how to get the URL of the active tab?

jquery 将 css 应用于除第二行之外的所有元素

javascript - 具有 ID 的 DOM 树元素会成为全局属性吗?