我有两个相关的下拉列表,其中第二个下拉列表中的内容取决于第一个下拉列表中的选择。例如,在下面的 HTML 代码中,您将首先选择应用程序方法。如果您选择 Aerial 作为应用方法,那么您将回答进一步的问题,例如 aerial size dist。否则,您需要回答地面喷雾类型。
因此,一旦网页加载完毕,两个二级下拉列表(空中尺寸距离和地面喷水类型)就会被隐藏。它们只有在第一个(应用方法)中做出相关选择时才会出现。
我能够在 jQuery 中实现此功能(在 jQuery 代码下方)。但是我的方法很愚蠢。我的问题是:
有没有办法选择整行,而不用计算它的序列 (nth-child())?我可以根据选择元素 ID 选择整行吗?例如,我可以先选择 $('#id_A') 然后将我的选择扩展到整行吗?
是否有更好的方法(循环?)来实现此隐藏或显示功能,而不是比较所有可能的选择 (($(this).val() == "X") )?
谢谢!
这是HTML代码,表单由Django生成:
<div class="articles">
<form method="GET" action=_output.html>
<table align="center">
<tr><th><label for="id_application_method">Application method:</label></th><td><select name="application_method" id="id_application_method">
<option value="">Pick first</option>
<option value="A">Aerial</option>
<option value="B">Ground</option>
</select></td></tr>
<tr><th><label for="id_A">Aerial Size Dist:</label></th><td><select name="aerial_size_dist" id="id_A">
<option value="A1" selected="selected">A1</option>
<option value="A2">A2</option>
</select></td></tr>
<tr><th><label for="id_B">Ground spray type:</label></th><td><select name="ground_spray_type" id="id_B">
<option value="B1" selected="selected">B1</option>
<option value="B2">B2</option>
</select></td></tr>
</table>
</form>
</div>
这是 jQuery 代码:
<script type="text/javascript" src=" https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script>$(function() {
$("tr:nth-child(2)").hide();
$("tr:nth-child(3)").hide();
$('#id_application_method').change(function() {
($(this).val() == "A") ?
$("tr:nth-child(2)").show() : $("tr:nth-child(2)").hide();
($(this).val() == "B") ?
$("tr:nth-child(3)").show() : $("tr:nth-child(3)").hide();
});});</script>
最佳答案
我认为 iKnowKungFoo 的回答非常直截了当(这是我的投票)。我注意到你说你的表单是由 Django 生成的。如果您不能直接修改生成的 HTML 标记,这里是您问题的另一种解决方案。
$(document).ready(function() {
var $aerialTr = $('#id_A').closest('tr').hide();
var $groundSprayTr = $('#id_B').closest('tr').hide();
$('#id_application_method').change(function() {
var selectedValue = $(this).val();
if(selectedValue === 'A') {
$aerialTr.show();
$groundSprayTr.hide();
} else if (selectedValue === 'B') {
$aerialTr.hide();
$groundSprayTr.show();
} else {
$aerialTr.hide();
$groundSprayTr.hide();
}
});
});
这是一个要测试的 jsFiddle:http://jsfiddle.net/willslab/n54cE/2/
它应该适用于您现有的标记。它根据选择框的当前 ID 选择 tr。如果更改这些 ID,则需要相应地修改选择器。
希望对您有所帮助!
编辑:这是受 iKnowKungFoo 启发的另一种“混合”方法。他的解决方案非常优雅,所以我将它与我自己的结合起来。这无需更改 HTML 或 CSS 即可工作。
$(document).ready(function() {
$('#id_A').closest('tr').addClass('method_options').hide();
$('#id_B').closest('tr').addClass('method_options').hide();
$('#id_application_method').change(function() {
$('tr.method_options').hide();
$('#id_' + $(this).val()).closest('tr').show();
});
});
jsFiddle 链接:http://jsfiddle.net/willslab/6ASJu/3/
关于javascript - jQuery:有条件地显示基于下拉框选择的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10200498/