我有以下小提琴:http://jsfiddle.net/4Ly1973u/。
这是我的HTML:
<article>
<select>
<option name='First' value='first'>First</option>
<option name='Second' value='second'>Second</option>
<option name='Third' value='third'>Third</option>
</select>
<div data-name='first' class='show'>
This one should show by default.
</div>
<div data-name='second'>
only visible when "second" is selected
</div>
<div data-name='third'>
only visible when "second" is selected
</div>
</article>
基本上,我希望默认情况下有第一个div节目,但是当你将select更改为second或third时,我希望它更改为该div。
我意识到我可以用if语句轻松做到这一点,但我可能有很多选择选项,所以我希望有一个更清晰的解决方案。或者这是唯一的方法吗?
答案 0 :(得分:3)
试试这个
$(function () {
$("select").on("change", function () {
$('.show').removeClass('show');
$('div[data-name="' + $(this).val() + '"]').addClass('show');
});
});
答案 1 :(得分:0)
这是一个工作小提琴:http://jsfiddle.net/4Ly1973u/3/
<article>
<select>
<option name='First' value='first'>First</option>
<option name='Second' value='second'>Second</option>
<option name='Third' value='third'>Third</option>
</select>
<div id='first' class='show'>This one should show by default.</div>
<div id='second' class='noshow'>only visible when "second" is selected</div>
<div id='third' class='noshow'>only visible when "third" is selected</div>
</article>
CSS
.show {
display: block;
}
.noshow {
display:none;
}
的jQuery
$(function () {
$("select").change(function () {
$('.show').removeClass('show').addClass('noshow');
var getValue = $("select option:selected").val();
$("#" + getValue).removeClass('noshow').addClass('show');
});
});