JQuery div可编辑

html代码:

<ol id="ol_group" class="list-group list_of_items"> 

<li class="list-group-item completed_item"> 

<div class="text_holder"> 

how are you? 

</div> 

<textarea rows="" cols=""></textarea>

<div class="btn-group pull-right"> 

<button class="delete btn btn-warning">Delete</button> 

<button class="edit btn btn-success">Edit</button> 

</div> 

<div class="checkbox"> 

<label> <input type="checkbox" class="pull-right"></label> 

</div> 

</li> 

</ol>

js:

$(document).on('click', '.btn-group .edit', function(){

//alert("asdfsd");

var divedit = $(this).parent().prev(); 

if (!divedit){

return; 

if (divedit.children("input").length > 0) {

return;

var mtext = divedit.text().substring(0, divedit.text().length-10); 

var inputIns = $("<input type='text'/>"); //创建input 输入框 

var oldtext = divedit.html(); //保存原有的值

inputIns.width(divedit.width()); //设置INPUT与DIV宽度一致 

inputIns.val(mtext); 

divedit.html(""); //删除原来单元格DIV内容 

inputIns.appendTo(divedit).focus().select(); //将需要插入的输入框代码插入DOM节点中

inputIns.click(function () {

return false; 

}); //处理回车和ESC事件 

inputIns.keyup(function (event) { 

var keycode = event.which; 

if (keycode == 13) { 

var newText = oldtext.replace(mtext, $(this).val()); 

divedit.html(newText); //设置新值 

if (keycode == 27) {

divedit.html(oldtext); //返回旧值 

}).blur( function (event) {

if($(this).val() != oldtext){ 

var newText = oldtext.replace(mtext, $(this).val()); 

divedit.html(newText); //设置新值

}else{ 

divedit.html(oldtext); 

} ); 

});

相关推荐