我试图创建这背后的代码时遇到了问题。我试图根据选择选项来显示/隐藏div,总共有4个选项。
有两个选择元素
<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>这些组合是
value1-value3 value1-value4
value2-value3 value2-value4
第二个select元素是空的,直到您从第一个select元素中进行选择,然后您可以从第二个元素中进行选择,并且它会显示该值的div。
div's应该是。
<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>你们能帮我做这个吗?
发布于 2013-10-03 21:36:00
我会给你的selects提供一些ID,为了这个例子,让我们分别使用sel1和sel2。我还会将option中的value更改为数字,否则将需要对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();
});小提琴:http://jsfiddle.net/b7Q8s/18/
发布于 2013-10-03 21:45:20
我自己的建议是:
/* 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();JS Fiddle demo。
这在设计上不会切换第二个select元素的显示,因为老实说,我看不出有这个必要,因为第一个select总是有一个selected,selected,option (即使只在默认情况下),否则,将需要选择一个非selected选项来启动select的change事件(即使您想选择已经选择的option )。
参考文献:
change().get().hide().map().not().show().siblings().发布于 2013-10-03 21:48:31
试一试
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
https://stackoverflow.com/questions/19160597
复制相似问题