我对jQuery / Javascript不是很实用,我知道如果我手动指定每个ID我该怎么做但我知道它不是一个好用的方法。
我在jQuery中搜索完全动态的方法,如果select元素(最初为空值)选择了一个选项(值不为空),则显示具有相同类的下一个select。
实施例
HTML:
<div id="sel1" class="sel" style="display: block;">
<select id="select1">
<option selected value>Default Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
<div id="sel2" class="sel">
<select id="select2">
<option selected value>Default Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
<div id="sel3" class="sel">
<select id="select3">
<option selected value>Default Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
这就是CSS:
.sel {
display: none;
}
答案 0 :(得分:1)
也许是这样:
$('select[id^=select]').on('change', function(){
if($(this).val().length > 0) {
$(this).closest('div.sel').next('div.sel').css('display', 'block');
}
});
.sel {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sel1" class="sel" style="display: block;">
<select id="select1">
<option selected value>Default Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
<div id="sel2" class="sel">
<select id="select2">
<option selected value>Default Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
<div id="sel3" class="sel">
<select id="select3">
<option selected value>Default Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
答案 1 :(得分:1)
这就是:
$('select').on('change', function(){
var nxt = $(this).parent('div').next(), // next element (div)
opt = $(this).val();
console.log( opt );
if( opt != '' ){
nxt.removeClass('sel');
} else {
nxt.addClass('sel');
}
});
&#13;
.sel {
display:none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="sel1" class="sel" style="display: block;">
<select id="select1">
<option selected value>Default Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
<div id="sel2" class="sel">
<select id="select2">
<option selected value>Default Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
<div id="sel3" class="sel">
<select id="select3">
<option selected value>Default Option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
</select>
</div>
&#13;