jQuery-如果是,请单击事件



我是jQuery的新手,现在只是在玩。我试图创建一个点击事件,每当点击时,<select></select>的属性"disabled"必须为true/false。

所以它从disabled[true]开始,当点击链接时,它会变成disabled[false]-很酷。但现在我不想用相同的链接将其设置回disabled[true]。

我的代码如下:

$('.enableSelects').click(function(){
    if($('select').is(':hidden')){
        $('select').attr('disabled', true);
    } else {
        $('select').attr('disabled', false);
    }
});

关于短版本:

$('.enableSelects').click(function(){
    $('select').prop('disabled', !$('select').prop('disabled'));
});​

以开头

$('select').prop('disabled', !$('select').prop('disabled'));
//          |                ||__________________________|
//          |                |  |
//          |                |  |_1) this will be evaluated first, resulting
//          |                |       in either 'true' or 'false'
//          |                |
//          |                |____2) the boolean value from above will then
//          |                        be inverted, and this new value will be
//          |                        used as the new value for disabled,
//          |                        which is then assigned
//          |
//          |_____________________3) using the 'prop' method

稍微好一点的版本:

$('.enableSelects').click(function(){
    //                            |-- 1) this function gets called by jQuery
    //                            |      automatically. The index and the current
    //                            |      value will be passed to it.
    //                            |      The return value will be assigned to the
    //                            |      property.
    //                            |
    $('select').prop('disabled', function (idx, current) {
       // we're returning the inverted current value
       return !current;
    });
});​

它基本上与上面相同,但我们正在减少必须评估的选择器的数量。

http://jsfiddle.net/k3sb8/1/

使用:disabled而不是:hidden,并且更喜欢.prop()而不是.attr()

此外,当文档中只有一个<select>时,当前方法也可以正常工作。当您有多个<select>元素时,请更改选择器。

您可能想了解.pr()与.attr()

尝试使用prop()而不是attr()

试着在评论中使用@Yoshi的小提琴:http://jsfiddle.net/k3sb8/

最新更新