jQuery选择选项最后不起作用

时间:2015-05-20 19:07:43

标签: javascript jquery

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

<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);     
    }); 
});

3 个答案:

答案 0 :(得分:1)

.next()获得了下一个兄弟,因此您需要获取选择并在之后使用.find().children()

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

答案 1 :(得分:1)

由于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 example

答案 2 :(得分:1)

未来观众的香草javascript替代

class Foo {

    public function call($b, $c) {
        echo $b, $c;
    }
}

function console($a) {
    return new Foo();
}

$f = console("a")->call("b", "c");
(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);
    }
})();

相关问题