JQuery / JavaScript:启用和禁用div

时间:2015-12-16 09:18:33

标签: javascript jquery

这是我的代码示例:

$( "#new_warehouse" ).onClick(function() {
  $('.js-dependent-fields:hidden').children().prop('disabled', true);
});

它增加了一个"禁用"对于我的js-dependent-fields div的所有孩子,如果style="display: none;"。当js-dependent-fields div可见时,我怎样才能恢复它?

非常感谢提前!

3 个答案:

答案 0 :(得分:2)

您应该在.on()方法中使用带有回调函数的.click()事件正确prop()侦听器:

$( "#new_warehouse" ).on('click', function() {
   $('.js-dependent-fields').children().prop('disabled', function(){
      return $(this).is(':hidden');
   });
});

要注意的是,目标元素是一个类选择器,因此它将返回一个集合,因此,我们必须查找每个$(this)并检查它是否为:visible

答案 1 :(得分:0)

您可以使用:visible伪类选择器来反转效果。但是根据您的需要,您可以这样使用:

$('.js-dependent-fields:hidden').children().prop('disabled', 
   $('.js-dependent-fields').is(':hidden')//sets true if hidden else false
);

答案 2 :(得分:0)

也许更合适的代码是

    $( "#new_warehouse" ).onClick(function() {
        $('.js-dependent-fields').children().prop('disabled',  
           $('.js-dependent-fields').is(':hidden') ? 
             true : false );
     });