これは、私がしばらくの間理解しようとした最もクールなことの 1 つです。
あなたのコードlive
は減価償却されたため、使用しないように最初に変更しました。
すべてのイベント ハンドラをdocument
in the document ready 関数に追加しました。必要に応じて委任。
次に、入力がダーティかどうかを示すフラグを作成する必要がありました。そうであり、新しくフォーカスされた要素が選択されていない場合、またはその逆の場合は、値を設定してフィールドを非表示にできるようにしました。
ここに私が思いついたものがあります:
$(document).ready(function () {
var oldValue = $('whileloopflagvalue');
$(document).find('.whileloopflagselect').hide();
$(document).find('.whileloopflaginput').hide();
$(document).on('focusin',function(event){
var theTarget = $(event.target);
var theInput = theTarget.parent().find('.whileloopflaginput');
var theSelect = theTarget.parent().find('.whileloopflagselect');
if(theInput.length > 0){
if(theTarget[0] == theInput[0] || theTarget[0] == theSelect[0]){
theInput.removeAttr('data-dirty');
}
}
});
$(document).on("focusout", function (event) {
var theTarget = $(event.target);
var theInput = theTarget.parent().find('.whileloopflaginput');
var theSelect = theTarget.parent().find('.whileloopflagselect');
setTimeout(function(){
if (theTarget[0] == theInput[0] || theTarget[0] == theSelect[0] ) {
if(theInput.attr('data-dirty') == 'dirty'){
theTarget.parent().find('.whileloopflagvalue').text(theInput.val());
theInput.hide();
theSelect.hide();
theTarget.parent().find('.whileloopflagvalue').show();
theInput.removeAttr('dirty');
}
}
}, 50);
});
$(document).on("click",".whileloopflagvalue", function (event) {
oldValue = $(this).text();
$(this).hide();
$(this).parent().find('.whileloopflagselect').show();
$(this).parent().find('.whileloopflaginput').show().focus();
});
$(document).on('change','.whileloopflagselect', function () {
var temp = $(this).attr("id");
$(this).parent().find(".whileloopflaginput").val($('#' + temp).find(":selected").text());
$(this).parent().find(".whileloopflaginput").attr('data-dirty','dirty');
$("#" + temp).val("").attr('selected', true);
});
$(document).on('input propertychange','.whileloopflaginput',function(){
$(this).attr('data-dirty','dirty');
});
});
したがって、テキスト ボックスに値を入力するか、ドロップダウンで値を選択すると、選択する次の要素が 2 つのうちの 1 つである限り、それらの間を好きなだけ移動できます。
ロスト フォーカス ハンドラーで を使用する理由はsetTimeout
、ブラウザーがfocusin
イベントを発生させる時間を確保するためです。これを行わないと、2 つのコントロールのうちの 1 つがフォーカスを失った後、どの要素がフォーカスされたかを知る方法がありません。
唯一の奇妙な点は、変更を加えないと非表示にならないことです。div をクリックした場合は、何かを変更する必要があります。