开发者

jquery unwrap Inner

开发者 https://www.devze.com 2023-02-04 16:22 出处:网络
I\'m trying to create a simple inline edit for a div box. When i dblclick on the div, i wrapInner with textarea tag. That makes it editable. But how can i unwrap the textarea tag when i click outsite

I'm trying to create a simple inline edit for a div box. When i dblclick on the div, i wrapInner with textarea tag. That makes it editable. But how can i unwrap the textarea tag when i click outsite the textarea field. Below is what i have which is not working. Also Should i use focusout, mouseout, mouseleave or any of them.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script> 

<div id="test" style="width:300px; height:200px;">
    testing
</div>

<script type="text/javascript">
$("#test").live({
    dblclick: function() {
        $("#test").wrapInner("<textarea/>")
    },
    mouseleave: function() {
        $("#test > textarea").unwrap()
    } 
});
<开发者_JAVA百科/script>


$("#test > textarea").unwrap() is unwrapping the textarea, therefore removing the div #test, rather than removing the textarea. Instead you want:

$("#test > textarea").contents().unwrap()

As you can see from this demo, the mouseleave will trigger immediately on any mouse movement after the wrapInner, so you probably want to bind the mouseleave to the textarea inside the doubleclick handler.


A few things you should probably do differently.

$("#test").dblclick( function() {
    $(this).wrapInner("<textarea/>").find('textarea').focus();
}).delegate('textarea','blur',function() {
    $(this).parent().text( this.value );
});
  • Bind the dblclick directly to #test
  • In the dblclick handler .find() the new textarea, and .focus() on it
  • Place a .delegate() handler on #test instead of using .live()
  • Use blur instead of mouseleave
  • In the blur handler, set the .text() of #test to the value of the textarea. (This is important in order to pick up the edits that were made.)

Example: http://jsfiddle.net/drQkp/1/


Example: http://jsfiddle.net/drQkp/2/

Here's an example that allows HTML to be typed into the textarea.

$("#test").dblclick(function() {
    $(this).html($("<textarea/>",{html:this.innerHTML})).find('textarea').focus();
}).delegate('textarea', 'blur', function() {
    $(this).parent().html(this.value);
});


Unwrap doesn't exist as far as I know. Once you have $('#test > textarea'), assign its contents to its parent.

It would be a lot less error-prone if you started off with the text "testing" inside a <span> or something, then copy the span's contents to a textarea, then back again.

0

精彩评论

暂无评论...
验证码 换一张
取 消