繁体   English   中英

jQuery选择选项最后一个不起作用

[英]jQuery select option last doesn't work

我有一个按钮和选项列表。 其想法是,当用户单击按钮时,默认选项将从禁用更改为最大值。 相反-如果未选中输入,则再次禁用默认值。 但是该值返回未定义。 如果我将第一个和最后一个更改为数值,则一切正常。 怎么了?

<input class="input" type="checkbox" value="1" name="select-pot[]">
<select id="select" name="q-count[]">
<option disabled selected> -- choose -- </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>

jQuery(function(){  

    jQuery(".input").click(function(){      

        var thefirst = jQuery(this).next('#select option:first').val();
        var thelast = jQuery(this).next('#select option:last').val();

        if( jQuery(this).is(':checked') )               
            jQuery(this).next('#select').val(thelast);      
        else        
            jQuery(this).next('#select').val(thefirst);     
    }); 
});

.next()获取下一个兄弟姐妹,所以你需要获得选择使用.find().children()算账:

var thefirst = jQuery(this).next('#select').find('option:first').val();
var thelast = jQuery(this).next('#select').find('option:last').val();

由于ID必须是唯一的,因此没有必要执行以下操作:

jQuery(this).next('#select option:first')

什么时候

jQuery('#select option:first')

就足够了,加上.next()会在这里失败,因为它会评估元素的同级并根据您传递的任何内容进行过滤,但是您的过滤器会导致它不匹配任何内容。

而是使用:

jQuery(".input").click(function () {
    var thefirst = jQuery('#select option:first').val();
    var thelast = jQuery('#select option:last').val();
    if (jQuery(this).is(':checked')) jQuery('#select').val(thelast);
    else jQuery('#select').val(thefirst);
});

jsFiddle示例

面向未来观看者的香草javascript替代

 (function () { "use strict"; var inputs = document.getElementsByClassName('input'), input; for (var i = 0; input = inputs[i]; i++) { input.addEventListener('click', function (e) { e.target.nextElementSibling.lastElementChild.selected = e.target.checked; e.target.nextElementSibling.firstElementChild.selected = !e.target.checked; }, false); } })(); 
 <input class="input" type="checkbox" value="1" name="select-pot[]"> <select id="select" name="q-count[]"> <option disabled selected>-- choose --</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> <option value="6">6</option> </select> 

暂无
暂无

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

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