gpt4 book ai didi

javascript - 如何使用 Javascript 缩短代码

转载 作者:行者123 更新时间:2023-12-03 12:41:38 25 4
gpt4 key购买 nike

我的任务就是我所做的,但我想知道选择框是否只有三个选项...如果它们是 5 个或 10 个选项,那么让我们想象一下 if else 条件如何下面可以是...

不仅如此,选择另一个选项后,其他选项的输入返回无值作为我的代码。

Demo

HTML:

<table>
<tr><td>123</td></tr>
<tr><td>456</td></tr>
<tr><td>...</td></tr>
<tr>
<td>
<select id="select_vehicle">
<option value="company_vehicle">Company Vehicle</option>
<option value="hiring_vehicle">Hiring Vehicle</option>
<option value="taxi">Taxi</option>
</select>
</td>
</tr>
<tr id="company_vehicle">
<td>Company Vehicle</td>
<td>
<input type="text" />
</td>
<td>
<input type="radio" name="vehicle" value="bus" />Bus</td>
<td>
<input type="radio" name="vehicle" value="train" />Trolley Car</td>
</tr>
<tr id="hiring_vehicle">
<td>Hiring Vehicle</td>
<td>
<input type="radio" name="vehicle" value="bus" />Bus</td>
<td>
<input type="radio" name="vehicle" value="train" />Trolley Car</td>
<td>
<input type="text" />
</td>
</tr>
<tr id="taxi">
<td>Taxi</td>
<td>
<input type="checkbox" name="vehicle" value="Taxi" />Taxi
</td>
</tr>
<tr><td>...</td></tr>
<tr><td>123</td></tr>
<tr><td>456</td></tr>
</table>

Javascript:

var select_vehicle = $("#select_vehicle");
// Set selected item
var set_selected_item = $(select_vehicle).val("company_vehicle");
// Hide options "Hiring Vehicle" & "Taxi"
var company_vehicle = $("#company_vehicle"); // Get id "Company Vehicle"
var hiring_vehicle = $("#hiring_vehicle"); // Get id "Hiring Vehicle"
hiring_vehicle.hide();
var taxi = $("#taxi"); // Get id "Taxi"
taxi.hide();

$(select_vehicle).on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
if (valueSelected == "company_vehicle") {
company_vehicle.show();
hiring_vehicle.hide();
taxi.hide();
$("#taxi input").removeAttr('checked');
$("#hiring_vehicle input").removeAttr('checked').val("");
} else if (valueSelected == "hiring_vehicle") {
company_vehicle.hide();
hiring_vehicle.show();
taxi.hide();
$("#company_vehicle input").removeAttr('checked').val("");
$("#taxi input").removeAttr('checked');
} else {
company_vehicle.hide();
hiring_vehicle.hide();
taxi.show();
$("#company_vehicle input").removeAttr('checked').val("");
$("#hiring_vehicle input").removeAttr('checked').val("");
}
});

最佳答案

你可以这样做:

$('#select_vehicle').change(function() {
var val = this.value;
$('#'+val).find('input[type="text"]').val('');
$('#'+val).find('input[type="radio"]').prop('checked',false);
$('#'+val).show().siblings('tr[id]').hide();
}).change();

<强> Updated Fiddle

关于javascript - 如何使用 Javascript 缩短代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23507757/

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