考虑在准备好的页面上运行此代码:
$("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 个元素的预期变化。
在这个重构中做错了什么?