Make span element “editable”

前端 未结 5 506
逝去的感伤
逝去的感伤 2021-01-01 14:47

I have a span element that I want to become editable upon double-click. (That is, the user can edit the text and it will save when s/he clicks outside.)

5条回答
  •  情话喂你
    2021-01-01 15:01

    I found many answers to be out of date on this topic, but adamb's was the easiest solution for me, thank you.

    However, his solution was bugged to fire multiple times due to not removing the keypress event along with the element.

    Here's the updated plugin using $.on() instead of $.bind() and with the keypress event handler being removed when the element is created again.

    $.fn.extend({
        editable: function() {
            var that = this,
                $edittextbox = $('').css('min-width', that.width()),
                submitChanges = function() {
                    that.html($edittextbox.val());
                    that.show();
                    that.trigger('editsubmit', [that.html()]);
                    $(document).off('click', submitChanges);
                    $edittextbox.detach();
                },
                tempVal;
            $edittextbox.click(function(event) {
                event.stopPropagation();
            });
    
            that.dblclick(function(e) {
                tempVal = that.html();
                $edittextbox.val(tempVal).insertBefore(that).off("keypress").on('keypress', function(e) {
                    if ($(this).val() !== '') {
                        var code = (e.keyCode ? e.keyCode : e.which);
                        if (code == 13) {
                            submitChanges();
                        }
                    }
                });
                that.hide();
                $(document).one("click", submitChanges);
            });
            return that;
        }
    });
    

    http://jsfiddle.net/Hbww2/142/

提交回复
热议问题