2013-03-12 3 views
1

시도해보십시오.> 입력하십시오. input 새 레이어에서 동적 업데이트 값>
2. 입력에서 값 표시를 클릭하고 다시 편집 할 수 있습니다.
http://jsfiddle.net/8yZhf/3/동적 업데이트 입력 텍스트 값

하지만, (갱신되지 않음)
때 마무리 편집 및 focusout 새로운 레이어를 추가 피하기 위해 사용 $('.input').off("focus")이 어떻게 focus 직전과 같은를 복구 할 수 있을지, 2에 붙어? 또는 더 좋은 생각?

var layer; 
$('.input').focus(function(){ 
    layer = $('.input_insert').children('div').length + 1; 
    $('<div class='+layer+'></div>').appendTo('.input_insert');// add layer 

    $('.input_insert').children('div').click(function(e){ 
     $('.input').val($(e.target).html()); 
     // $('.input').off("focus"); 
    }) 
    return layer;// return layer count for keyup, focusout 
}) 
$('.input').keyup(function(e){ 
    $('.'+layer).html(this.value); 
}) 
$('.input').focusout(function(){ 
    $("input[class='input']").val(''); 
    if($('.'+layer).html() == ''){// check if empty 
     $('.'+layer).remove(); 
    } 
}) 

HTML

<input type="text" class="input"> 
<div class="input_insert"></div>// container 

답변

0

TLDR : jsFiddle Demo

먼저 코드에서 간단한 문제가 있었다. 이 코드를 사용하여 모든 요소에 클릭 이벤트를 다시 할당했습니다.

$('.input_insert').children('div').click(function(){ 
    $('.input').val($('.'+layer).html()); 
    // $('.input').off("focus"); 
}) 

첫 번째 문제는 새 요소가 클릭 이벤트에 연결되도록하는 것입니다.

다음 문제는 가변 추적 레이어가 하나뿐이므로 가장 최근의 레이어 만 사용 된 것이 었습니다. 이는 추가 추적 변수를 구현하여 해결할 수 있습니다.

HTML 같은

var layer; 
var target = -1;//when not -1, this indicates a layer is being edited 
$('.input').focus(function(){ 
layer = $('.input_insert').children('div').length + 1; 
//save the value of the layer for use on click event 
var current = layer; 
$('<div class='+layer+'></div>').appendTo('.input_insert');// add layer 
//wire click only to the new layer 
$('.'+current).click(function(){ 
    $('.input').val($(this).html()); 
    //indicate that this layer is the edit target when clicked 
    target = current; 
}); 
return layer;// return layer count for keyup, focusout 
}); 
$('.input').keyup(function(e){ 
//check if there is a layer being edited 
if(target > -1){//layer edit 
    $('.'+target).html(this.value); 
}else{//new layer 
    $('.'+layer).html(this.value); 
} 
}); 
$('.input').focusout(function(){ 
//reset target because there is no current edit 
target = -1; 
$("input[class='input']").val(''); 
    if($('.'+layer).html() == ''){// check if empty 
    $('.'+layer).remove(); 
    } 
}); 
0

나는 약간 다른 방식으로 그것을 할 것

JS 위와 같이

$('input').on('keypressed', function(e) { 
    $('.input_insert:last-child').text($(this).val()) 
}).on('blur', function(e) { 
    var val = $(this).val() 
    , lastInsert = $('.input_insert:last-child').text('') 
    , newInsert = $('<div />').addClass('input_insert') 
          .text(val).insertBefore(lastInsert) 
    $(this).val('') 
})