2014-05-15 35 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/ –

相關問題