gpt4 book ai didi

javascript - 当其中任何一个发生变化时,对许多下拉菜单的内容求和

转载 作者:行者123 更新时间:2023-11-30 18:05:52 27 4
gpt4 key购买 nike

我在一个页面上有几个下拉菜单,它们都包含一些数字。当用户更改其中任何一个时,我需要遍历所有这些并对所有数字求和。

我如何使用 jQuery 做到这一点?

<select id="number1">
<option value="1">1</option>
<option value="3">3</option>
</select>
<select id="number2">
<option value="1">1</option>
<option value="3">3</option>
</select>
<select id="number4">
<option value="1">1</option>
<option value="3">3</option>
</select>

我试过类似的方法:

$('select[id*="number"].change(function() { // when any one dropdown change

$('select[id*="number"].change(function() { // go through them all
var current = $(this);

// add current value to array
});
});

$.each(arr,function() {
total += this; // sum items
});

但它并没有像预期的那样工作。有小费吗?谢谢。

最佳答案

您似乎试图将对 change() 的调用嵌套在彼此内部。第二次不要使用 change(),使用 .each()。 (此外,您还缺少每个选择器末尾的结束 '),因此您的代码根本无法运行。)

change() 处理程序之外循环遍历数组没有意义,因为该代码何时真正运行?

试试这个:

$('select[id*="number"]').change(function() { // when any one dropdown change
total = 0; // reset the total
$('select[id*="number"]').each(function() { // go through them all
total += +this.value; // use unary plus to convert string value for addition
});
// do something with total here
});

演示:http://jsfiddle.net/nnnnnn/8L9Hz/

关于javascript - 当其中任何一个发生变化时,对许多下拉菜单的内容求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15829289/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com