這是我曾嘗試在一段時間才能找出最酷的事情之一。
我先更改了您的代碼,因爲它已折舊,因此不再使用live
。
我在文件就緒功能中將所有事件處理程序添加到document
;必要時委派。
然後我不得不創建一個標誌來告訴輸入是否髒。如果是,並且新聚焦的元素不是選擇,反之亦然,那麼我允許它設置值並隱藏字段。
here is what I came up with:
$(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');
});
});
如果您在文本框中輸入一個值,或選擇在下拉列表中值下降,只要你選擇下一個元素是一個兩個,那麼你可以所以現在在他們之間移動儘可能多。
丟失焦點處理程序中setTimeout
的原因是允許瀏覽器觸發focusin
事件。如果你沒有這樣做,那麼在兩個控件中的一個失去焦點後,就無法知道哪個元素得到了焦點。
唯一古怪的是,如果你不做任何改變,那麼它就不會隱藏。如果你點擊div,你必須改變一些東西。
感謝您的協助波伊恩。 – 2013-03-21 14:18:07