When click change to text-area, When outside click

2019-05-27 03:47发布

问题:

I am trying to make a function like PHPadmin what they are using on when showing the table, when click the div filed, change to text-area, and when click outside of the div, change it back to the div filed. The code below is wrong, I cannot change back to the div filed when I click outside. Please help me to improve the code.

JS:

$('#editor #gird_edit').bind({
  click: function() {
            $(this).html('<textarea id="gird_edit">'+$(this).text()+'</textarea>');
  },
  blur: function() {
            $(this).html('<div id="gird_edit">'+$(this).text()+'</div>');
  }
});

Html:

<div id='editor'>
<div id='gird_edit'>hallo world</div>
<div id='gird_edit'>hallo world 2</div>
<div id='gird_edit'>hallo world 3</div>
</div>

I only have 8 reputations, I cannot vote you back. However, I sincerely appreciate your helps!

回答1:

see jsfiddle

updated jsfiddle

when $(this).html(textarea) is done, div is already blur. so the onBlur didn't work

$('#editor #gird_edit').bind({
    click: function() {
        var tex = $(this).text();
        var textarea = $('<textarea id="gird_edit">'+tex+'</textarea>');
        $(this).html(textarea);
        textarea.focus();
        textarea.blur(function(){
            var currentText = textarea.val();
            if(currentText == tex)//not change
                textarea.parent().text(tex);
            else //changed
                alert(currentText);
        });
    }
});

edit 3:

else{
    textarea.parent().text(currentText);
    //something else
}

find more jquery API



回答2:

check this jsbin i just made, if you need anything else i'm glad to help.



回答3:

When you first click on the #gird_edit it is a div, so this is a div, and you can replace its contents to change things. However, when you blur away #gird_edit is a textarea, so if you change its contents you're not really changing what you want to change (your just changing the insides of your textarea).

What you want to change is the div that's around the textarea, ie. the "parent" of that textarea. In other words, try:

blur: function() {
        $(this).parent().html('<div id="gird_edit">'+$(this).text()+'</div>');
}