2011-01-13 42 views
7

我正在嘗試爲div框創建一個簡單的內聯編輯。當我在div上點擊時,我用textarea標記wrapInner。這使它可編輯。但是,當我點擊outsite textarea字段時,如何解開textarea標記。以下是我有哪些不起作用。另外我應該使用focusout,mouseout,mouseleave或其中任何一個。jquery展開內部

<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() 
    } 
}); 
</script> 

回答

4

有幾件事你應該做的不同。

$("#test").dblclick(function() { 
    $(this).wrapInner("<textarea/>").find('textarea').focus(); 
}).delegate('textarea','blur',function() { 
    $(this).parent().text(this.value); 
}); 
  • 綁定dblclick直接#test
  • dblclick處理.find()textarea,並.focus()
  • 將一個.delegate()處理程序,而不是使用.live()
  • 使用blur而不是在#testmouseleave
  • blur處理程序中,將.text()#test設置爲textareavalue。 (這是爲了拾取所做的修改是很重要的。)

實施例:http://jsfiddle.net/drQkp/1/


實施例:http://jsfiddle.net/drQkp/2/

下面是一個例子,它允許HTML到被輸入到textarea中。

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

不折不就我知道的存在。一旦你有$('#test > textarea'),將其內容分配給其父。

如果您從<span>或其他內容中的文本「測試」開始,然後將該範圍的內容複製到textarea,然後再返回,那麼它會少得多。

+0

不折不存在http://api.jquery.com/unwrap/ – Hussein 2011-01-13 02:15:25

+0

@alex糟糕!但是,它適用於DOM元素,而不是它們的值內容。 – 2011-01-13 09:37:40

11

$("#test > textarea").unwrap()正在解開textarea,因此刪除了div #test,而不是刪除textarea。相反,你想:

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

正如你可以從這個demo看到,鼠標離開會立即wrapInner後觸發任何鼠標移動,所以你可能希望將鼠標離開綁定到雙擊處理程序中的文本區域。