jQuery查找具有下一个特定类型元素的元素

jQuery find element with next element of specific type

本文关键字:元素 类型 下一个 查找 jQuery      更新时间:2023-09-26

我有包含不同输入元素的"组件"。这些组件有一个复选框,允许用户在元素上切换启用/禁用。这是当前禁用输入和选择的代码。

 $(".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>

要禁用此元素,我需要取消绑定span unbind("click");的click

我该怎么做?如果input的next()元素是一个span,我需要取消它的绑定。

首先可以通过缓存选择器来DRY代码。其次,我不会取消绑定span的click处理程序,因为当您需要重新附加它时,这将使它变得很痛苦。相反,我将使用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
    }
});