2014-05-15 127 views
1

我拥有包含不同输入元素的“组件”。这些组件有一个复选框,允许用户切换元素的启用/禁用。这是当前禁用输入和选择的代码。jQuery查找具有特定类型的下一个元素的元素

$(".activeComponentToggle input:checkbox").on("change", function() { 
       if ($(this).is(':checked')) { 
        $(this).closest("div.component").addClass("activeComponentWell"); 
        $(this).closest("div.component").removeClass("inactiveComponentWell"); 
        $(this).closest("div.component").find("input.form-control").prop('disabled', false); 
        $(this).closest("div.component").find("select.form-control").prop('disabled', false); 
       } else { 
        $(this).closest("div.component").addClass("inactiveComponentWell"); 
        $(this).closest("div.component").removeClass("activeComponentWell"); 
        $(this).closest("div.component").find("input.form-control").prop('disabled', true); 
        $(this).closest("div.component").find("select.form-control").prop('disabled', true); 
       } 
      }); 

现在我也有这样的HTML元素

<div class="input-group date" id="datetimepickerRanged11"> 
<input type="text" id="datepickerRanged811" class="form-control"> 
<span class="input-group-addon"><span class="glyphicon-calendar glyphicon"></span></span></div> 

要禁用这个元素,我需要解除绑定跨度unbind("click");

我怎样才能做到这一点的点击?如果输入的next()元素是一个跨度,我需要解除它。

+1

您可以使用nextAll(),您可以指定元素的您正在寻找的类型。对于span:nextAll('span:first'),同样适用于prevAll() –

+1

另外,我建议你阅读[DRY](http://en.wikipedia.org/wiki/Don't_repeat_yourself)和用一个替换8个对'$(this).closest(“div.component”)'的调用。你也可能想了解[jQuery chaining](http://tobiasahlin.com/blog/quick-guide-chaining-in-jquery/)。 – jfriend00

+0

@KamleshKushwaha可以工作,但只适用于第一个具有跨度的元素。 –

回答

1

首先,您可以通过缓存选择器来干掉代码。其次,我不会解除对跨度的点击处理程序的绑定,因为当您需要重新附加它时,它会变得很痛苦。相反,我会使用data属性来指示span点击是否被阻止。事情是这样的:

$(".activeComponentToggle input:checkbox").on("change", function() { 
    var $component = $(this).closest("div.component"); 
    if ($(this).is(':checked')) { 
     $component 
      .addClass("activeComponentWell")  
      .removeClass("inactiveComponentWell"); 
      .find("input.form-control").prop('disabled', false).end() 
      .find("select.form-control").prop('disabled', false).end() 
      .find('span.input-group-addon').data('disabled', false) 
    } 
    else { 
     $component 
      .addClass("inactiveComponentWell") 
      .removeClass("activeComponentWell") 
      .find("input.form-control").prop('disabled', true).end() 
      .find("select.form-control").prop('disabled', true).end() 
      .find('span.input-group-addon').data('disabled', true) 

    } 
}); 

然后在span单击处理:

$('span.input-group-addon').click(function() { 
    if (!$(this).data('disabled')) { 
     // do something 
    } 
}); 
+0

谢谢,很好的回答。我现在遇到一些问题,我想禁用它的引导datetimerpicker,示例代码在这里:http://tarruda.github.io/bootstrap-datetimepicker/ –

相关问题