我在尝试创建此背后的代码时遇到问题。我试图根据选择选项显示/隐藏div,总共有4个选项。
有2个选择元素
<select>
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
</select>
<select>
<option value="value3">Value 3</option>
<option value="value4">Value 4</option>
</select>
组合将是
值1-VALUE3 值1-VALUE4
值2-值3 值2-VALUE4
第二个选择元素为空,直到您从第一个选择元素中进行选择,然后您可以从第二个元素中进行选择,并显示该值的div。
div将是。
<div id="value-1-3">value1-value3</div>
<div id="value-1-4">value1-value4</div>
<div id="value-2-3">value2-value3</div>
<div id="value-2-4">value2-value4</div>
你们可以帮助我这样做吗?。
答案 0 :(得分:2)
我会向您的selects
提供一些ID,为了这个示例,我们分别使用sel1
和sel2
。我也会将value
中的option
更改为只是一个数字,否则将需要修剪value
或正则表达式:
$("#sel1").change(function() {
$("#sel2").prop("disabled", false); //enable the second select
$("#sel2").change(); //trigger a change event on select2
});
$("#sel2").change(function() {
//Gather your select values
var sel1Value = $("#sel1").val();
var sel2Value = this.value;
//Concatenate a selector and show it!
$("div").hide(); //hide previously shown divs
$("#value-" + sel1Value + "-" + sel2Value).show();
});
答案 1 :(得分:0)
我自己的建议是:
/* a more precise selector would be useful, whether by specifying an ancestor or
by adding an id to the select elements. Binding the change event-handler: */
$('select').change(function(){
/* creating the id of the relevant element to show using map(),
to the string 'value-' plus whatever the map(), and get(), methods return: */
$('#value-' + $('select option:selected').map(function(){
// removing all non-numeric characters, returning the numbers:
return this.value.replace(/\D+/g,'');
/* forming an array with get(),
joining the array elements together with hyphens, with join(),
showing the element whose id matches the created string
selecting siblings, removing the select elements from that selection,
and hiding them: */
}).get().join('-')).show().siblings().not('select').hide();
/* triggering the change event so the above always only shows/hides
the relevant elements on loading the DOM: */
}).change();
这并没有按设计切换第二个选择元素的显示,因为老实说我没有看到需要,因为第一个select
将总是有一个选定的,option
(即使只是默认情况下),否则,将需要选择一个未选择的选项来启动选择的change
事件(即使您要选择已经的<{1}} 已选中)。
参考文献:
答案 2 :(得分:0)
尝试
var $divs = $('div[id^="value-"]').hide();
var $sel1 = $('#sel1').one('change', function(){
$sel2.prop('disabled', false);
});
var $sel2 = $('#sel2');
$sel1.add($sel2).change(function(){
var p1 = $sel1.val().replace(/\D+/, '');
var p2 = $sel2.val().replace(/\D+/, '');
$divs.hide();
$('#value-' + p1 + '-' + p2).show();
})
演示:Fiddle