1

>1.input新しいレイヤーに動的更新値を入力>
2.入力に表示されている値をレイヤーをクリックして、再度編集できるようにします。
http://jsfiddle.net/8yZhf/3/

しかし、私は2で立ち往生しています。$('.input').off("focus")新しいレイヤーの追加(更新ではない)を回避するために使用する場合、
編集を終了するときに、以前と同じようにfocusout回復するにはどうすればよいですか?focusまたは他のより良いアイデア?

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
4

2 に答える 2

0

TLDR:jsFiddleデモ

最初はコードに単純な問題がありました。ここでは、このコードを使用してすべての要素にクリックイベントを再割り当てしていました

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

したがって、最初の問題は、クリックイベントに新しい要素を接続することだけに対処することでした。

次の問題は、可変追跡レイヤーが1つしかないため、最新のレイヤーのみが使用されたことです。これは、追加の追跡変数を実装することで対処できます。

上記と同じhtml

js

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();
  }
});
于 2013-03-13T00:01:56.650 に答える
0

少し違うやり方でやります

$('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('')
})
于 2013-03-13T00:12:10.027 に答える