gpt4 book ai didi

javascript - 选择选项时更改变量值,不再选择时返回之前的值

转载 作者:行者123 更新时间:2023-11-28 09:25:50 27 4
gpt4 key购买 nike

我需要根据选择的下拉菜单选项来更新变量的值(在示例中我将其称为“tot”)。如果我选择选项 1 或 2,tot 必须增加 10,如果我选择选项 3,则变量“tot”不得增加。如果我选择选项 1,然后我改变主意并选择选项 3,则必须恢复 Tot 的值。

这是选择的 html

<select name='hello' id='hello'>
<option>Select an option...</option>
<option id='one'>One</option>
<option id='two'>Two</option>
<option id='three'>Three</option>
</select>

这是我编写的 jquery 脚本。我想我不明白 .change 函数的功能,因为它没有按我的预期工作。

var extra = 0;
var tot = 0;

$(document).ready(function () {
$('#hello').change(function(){
if($('#one').is(':selected')) {
extra = 10;
}
else if($('#two').is(':selected')) {
extra = 10;
}
else if($('#three').is(':selected')) {
extra = 0;
}
tot = tot + extra;
});
});

最佳答案

或者(如果我正确理解了你的意思)......

var tot = 120;  //some number picked at random
var helloed = false; // flag for whether incremented

$(document).ready(function(){
$("#hello").change(function(){
var sel = $(this).find(":selected").attr("id")
if (sel == "one" || sel =="two" ) {
if (!helloed) {
tot += 10;
helloed = true;
}
} else { // 'three' selected
if (helloed) {
tot -= 10;
helloed = false;
}
}
alert ("Tot is now " + tot);
});
});

如果有更多选项,我会选择 switch 而不是 IF,但这对于本例来说就足够了

关于javascript - 选择选项时更改变量值,不再选择时返回之前的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14430317/

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