[英]jQuery find element with next element of specific type
我有包含不同输入元素的“组件”。 这些组件具有一个复选框,允许用户切换元素的启用/禁用。 这是当前禁用输入和选择的代码。
$(".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()元素是一个范围,则需要取消绑定。
首先,您可以通过缓存选择器来干燥代码。 其次,我不会取消跨度的单击处理程序的绑定,因为当您需要重新附加它时,它将使您很痛苦。 相反,我将使用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
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.