0

考虑在准备好的页面上运行此代码:

$("input.extraOption[checked]").each(function() {   
        console.log($(this));
        $(this).closest('.questionRow').find('.date').attr("disabled", true);
        $(this).closest('.questionRow').find('.dateSpan').hide();
        $(this).closest('.questionRow').find('.date').val("");
        $(this).closest('.questionRow').find('.textareaResize').attr("disabled", true);
        $(this).closest('.questionRow').find('.textareaResize').val("");
        $(this).closest('.questionRow').find('.text').attr("disabled", true);
        $(this).closest('.questionRow').find('.text').val("");
        $(this).closest('.questionRow').find('.checkbox').attr("disabled", true);

    });

我想重构这些调用,因为它们也在其他地方使用,所以我创建了以下函数:

jQuery.fn.extend({
    toggleAnswers: function (disable) {
        var group = $(this);
        group.find('.date').attr("disabled", disable);
        group.find('.date').val("");
        group.find('.textareaResize').attr("disabled", disable);
        group.find('.textareaResize').val("");
        group.find('.text').attr("disabled", disable);
        group.find('.text').val("");
        group.find('.checkbox').attr("disabled", disable);
        if(checkedStatus === true){
            group.find('.dateSpan').hide();
        }else{
            group.find('.dateSpan').show();
        }
    return group;
    }
});

然后我继续更改 8 $(this).closest(...) 调用:

$(this).closest('.questionRow').toggleAnswers(true);

这就是问题所在:在一个有 5 个与选择器匹配的元素的页面上,只有第一个会发生变化(换句话说,我只有一个 console.log)!在重构之前,我得到了所有 5 个元素的预期变化。

在这个重构中做错了什么?

4

1 回答 1

1

checkStatus没有在任何地方定义,导致异常。你似乎想disable改用。

附带说明一下,this已经引用了调用此方法的 jQuery 集合,因此包装this在 jQuery 对象 ( $(this)) 中是多余的/不必要的。请注意,这专门在$.fn方法内部,而不是普通的 jQuery 方法。例如,内部事件处理程序this是指 DOM 元素,因此您需要将其包装起来$(this)以便在其上调用 jQuery 方法。

此外,应使用以下方法禁用元素.prop("disabled", true/false).prop() 与 .attr()

您还可以组合调用相同 jQuery 方法的任何选择器。例如,group.find('.date').val("");group.find('.text').val("");可以组合成:group.find(".date, .text").val("");

将所有这些建议放在一起,以及迭代this(为了一致性和可扩展性),这就是我要使用的:

jQuery.fn.extend({
    toggleAnswers: function (disable) {
        return this.each(function (idx, el) {
            var $group = $(el);
            $group.find(".date, .text, .textareaResize, .checkbox").prop("disabled", disable);
            $group.find(".date, .textareaResize, .text").val("");
            $group.find(".dateSpan").toggle(!disable);
        });
    }
});

根据您的使用方式,我将其设置为:

var targets = $("input.extraOption[checked]"),
    toggler = function () {
        $(this).closest(".questionRow").toggleAnswers(this.checked);
    };

targets.each(toggler).on("click", toggler);

演示:http: //jsfiddle.net/XdNDA/

于 2013-08-22T18:30:52.397 回答