gpt4 book ai didi

javascript - 使用 JavaScript Switch Case 时遇到问题

转载 作者:行者123 更新时间:2023-11-28 12:26:20 25 4
gpt4 key购买 nike

<强> Demo

您能否告诉我在下面的情况下如何使用 JavaScript Switch Case?

<input type="checkbox" name="animal" value="Cat" id="cats" />Cats<br />
<input type="checkbox" name="animal" value="Dog" id="dogs" />Dogs<br />
<input type="checkbox" name="animal" value="Bird" id="birds" />Birds<br />

<script>
$('input:checkbox').change(function () {
if ($(this).is(':checked')) {
if (this.id == "cats") {
alert("Cat Selected");
}
if (this.id == "dogs") {
alert("Dogs Selected");
}
if (this.id == "birds") {
alert("Birds Selected");
}
} else {
alert('Un Checked');
}
});
</script>

我真的需要学习如何在这样的真实场景中使用 JavaScript Switch Case,谢谢。

最佳答案

像这样吗?

$('input:checkbox').change(function () {
if ($(this).is(':checked')) {
switch (this.id){
case 'cats':
alert("Cat Selected");
break;
case 'dogs':
alert("Dogs Selected");
break;
case 'birds':
alert("Birds Selected");
break;
}
} else {
alert('Un Checked');
}
});

http://jsfiddle.net/ycd5pd4b/1/

更新:

根据评论 - 处理未检查的项目。您可以尝试使用此代码,而实际上您不需要 IF 条件。理论上甚至不需要开关,但取决于您的意图。

$('input:checkbox').change(function () {
var checked = $(this).is(':checked'), strChecked = 'checked',
strUnchecked = 'unchecked',
result = (checked ? (this.id + ' ' + strChecked) : (this.id + ' ' + strUnchecked));

// in fact this switch is useless..
switch (this.id){
case 'cats':
alert(result);
break;
case 'dogs':
alert(result);
break;
case 'birds':
alert(result);
break;
}
// you can just call this
// alert(result);
});

jsfiddle: http://jsfiddle.net/ycd5pd4b/2/

关于javascript - 使用 JavaScript Switch Case 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28085926/

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