gpt4 book ai didi

javascript - 每次从选择框中选择不同的选项时想要调用不同的 Javascript 方法

转载 作者:行者123 更新时间:2023-11-30 12:55:08 25 4
gpt4 key购买 nike

我有一个选择框,其中包含最近和流行两个选项,要求是,如果我选择最近,那么调用后端应该去获得相应的响应,对于流行也应该发生同样的情况。我已经回答了这里提出的许多问题,但找不到我正在寻找的确切答案。我当前的代码如下所示

<select class="recentOrPopular" name="mostpopular">
<option value="recent">Recent</option>
<option value="popular">Popular</option>
</select>

这是带有两个选项的简单 html,JavaScript 是:

if($('.recentOrPopular').val('recent')){
this.myrecentFunction();
}

$( ".recentOrPopular" ).change(function() {
if($('.recentOrPopular').val('popular')){
this.myPopularFunction();
}
if($('.recentOrPopular').val('recent')){
this.myrecentFunction();
}
});

所以默认情况下,最初会调用 myrecentFunction,但如果我更改选项,则会调用两个 if block 。 sme 类 fiddle 的链接是:here

最佳答案

您正在使用 .val(value) 设置值而不是阅读它进行比较

$(".recentOrPopular").change(function () {
var value = $(this).val();
if (value == 'popular') {
this.myPopularFunction();
} else if (value == 'recent') {
this.myrecentFunction();
}
});

使用开关

$(".recentOrPopular").change(function () {
var value = $(this).val();
switch (value) {
case 'popular':
this.myPopularFunction();
break;
case 'recent':
this.myrecentFunction();
break;
}
});

关于javascript - 每次从选择框中选择不同的选项时想要调用不同的 Javascript 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19442434/

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