ページの準備ができて実行されているこのコードを検討してください。
$("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 は 1 つしか取得されません)。リファクタリングの前に、5 つの要素すべてで期待どおりの変更が得られます。
このリファクタリングで間違っていることは何ですか?