[英]jQuery show/hide div with select options by name
I am having problem with showing/hiding my divs, which depent on selected value "name". 我在显示/隐藏div时遇到问题,该div取决于所选值“名称”。
Here is my HTML : 这是我的HTML:
<select name="selectVehicle" id="selectVehicle">
<option name="A" value="A">Car</option>
<option name="C" value="C">Truck</option>
</select>
<div id="A" class="vehicle">+Car+</div>
<div id="C" class="vehicle" style="display:none;">+Truck+</div>
...And my JS: ...还有我的JS:
$(function() {
$('#selectVehicle').change(function(){
$('.vehicle').hide();
$('#' + $(this).val()).show();
});
});
https://jsfiddle.net/wgee7ekh/1/ https://jsfiddle.net/wgee7ekh/1/
You can use :selected
to get the name
property of selected option. 您可以使用:selected
获取所选选项的name
属性。
$('#selectVehicle').change(function(){
$('.vehicle').hide();
$('#' + $(':selected',this).attr('name')).show();
});
The issue is that this
in your .change()
event handler is the <select>
element, not the selected <option>
element, but you want the name
attribute from the selected <option>
element. 问题是, this
在您的.change()
事件处理程序是<select>
元素,而不是选择<option>
元素,但你想要的name
从选定的属性<option>
元素。
You can get the selected option in a couple ways. 您可以通过两种方式获得所选选项。 In plain Javascript, you can use the .options
array and the .selectedIndex
property as in this.options[this.selectedIndex]
to get it like this: 在纯Javascript中,您可以像在this.options[this.selectedIndex]
那样使用.options
数组和.selectedIndex
属性来获得它,如下所示:
$(function() {
$('#selectVehicle').change(function(){
$('.vehicle').hide();
$('#' + this.options[this.selectedIndex].getAttribute("name")).show();
});
});
jsFiddle: https://jsfiddle.net/jfriend00/upswtfeg/ jsFiddle: https ://jsfiddle.net/jfriend00/upswtfeg/
or in jQuery, you can use the pseudo-selector :selected
to find it like this: 或在jQuery中,您可以使用伪选择器:selected
来查找它,如下所示:
$(function() {
$('#selectVehicle').change(function(){
$('.vehicle').hide();
$('#' + $(this).find('option:selected').attr('name')).show();
});
});
jsFiddle: https://jsfiddle.net/jfriend00/ywkd25w8/ jsFiddle: https ://jsfiddle.net/jfriend00/ywkd25w8/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.