Seeing as how this page is both 3 years old and the first result in a Google search I thought it was due a more current answer. Given the weight and complexity of the plugin options above I thought a simpler, no-frills, more direct solution might also be appreciated for those looking for alternatives.
This replaces the table cell with a text input and calls custom events so you can handle whatever use case you want on save, close, blur, etc...
In this case the only way to change the information in the cell is to press enter, but you can customize that if you like, eg. you might want to save on blur.
In this example you can also press the Esc key to stop editing and put the cell back to what it was. You can customize that if you like.
This example works on a single click, but some people prefer doubleclick, your choice.
$.fn.makeEditable = function() {
$(this).on('click',function(){
if($(this).find('input').is(':focus')) return this;
var cell = $(this);
var content = $(this).html();
$(this).html('<input type="text" value="' + $(this).html() + '" />')
.find('input')
.trigger('focus')
.on({
'blur': function(){
$(this).trigger('closeEditable');
},
'keyup':function(e){
if(e.which == '13'){ // enter
$(this).trigger('saveEditable');
} else if(e.which == '27'){ // escape
$(this).trigger('closeEditable');
}
},
'closeEditable':function(){
cell.html(content);
},
'saveEditable':function(){
content = $(this).val();
$(this).trigger('closeEditable');
}
});
});
return this;
}
You can selectively apply the editable cells by attaching them like so, or whatever makes sense for your case.
$('.editable').makeEditable();
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…