繁体   English   中英

jQuery按名称显示/隐藏div和选择选项

[英]jQuery show/hide div with select options by name

我在显示/隐藏div时遇到问题,该div取决于所选值“名称”。

这是我的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>

...还有我的JS:

    $(function() {
        $('#selectVehicle').change(function(){
            $('.vehicle').hide();
            $('#' + $(this).val()).show();
        });
    });

https://jsfiddle.net/wgee7ekh/1/

这是您根据name属性选择的方式:

$(function() {
    $('#selectVehicle').change(function(){
        $('.vehicle').hide();
        $('#' + $(this).find('option:selected').attr('name')).show();
    });
});

这是一个JSFiddle

您可以使用:selected获取所选选项的name属性。

$('#selectVehicle').change(function(){
    $('.vehicle').hide();
    $('#' + $(':selected',this).attr('name')).show();
});

更新小提琴

问题是, this在您的.change()事件处理程序是<select>元素,而不是选择<option>元素,但你想要的name从选定的属性<option>元素。

您可以通过两种方式获得所选选项。 在纯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/

或在jQuery中,您可以使用伪选择器:selected来查找它,如下所示:

$(function() {
    $('#selectVehicle').change(function(){
        $('.vehicle').hide();
        $('#' + $(this).find('option:selected').attr('name')).show();
    });
});

jsFiddle: https ://jsfiddle.net/jfriend00/ywkd25w8/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM