2011-02-11 39 views
2

我有一个文本区域,我正在填充html代码,供人们从中删除&粘贴。这个textarea使用JQuery和.html()来“填充”。与“人口”从<div>页面例子在其他地方来:JQuery .html()打印准确的html代码

的div“举办的‘人口’

<div id="populationhold">this is the html to copy</div> 

那么‘JQ的魔术’‘点击’按钮,然后填充textarea的

$('#button').click(function(){ 
updatefunction(); 
}); 

和updatefunction是有点像这样:

function updatefunction(){ 
$('#textarea').html($('#populationhold').val(); }); 
} 

现在如果我尝试像这样的东西来填充:

$('#textarea').html('this is the <br />html to copy'); 

的html的()将只打印<br><br />。我试过了(用我的方式逃避<br \/>,但那不行。建议请,因为我必须“产生”干净的XHTML代码不仅仅是HTML4代码

下一位是概率只是相同,但有点更复杂的 - 因此上面的领导到这个

为“用户”我的网站,你将能够从代码示例添加/删除位:

<div id="populationhold"> 
<div class="codebit1">this is the <br />html to copy</div> 
\n<br/>\ 
<div class="codebit2">this is more <br />html to copy</div> 
</div> 

$('#button').click(function(){ 
$('#textarea').html($('#populationhold').val(); 
}); 

填充textarea的是罚款和工作,所以“90%”的删除。这是这样的:

$('#deletebutton').click(function(){  
$('.codebit1').remove(); 
// This removes .codebit1 from #populationhold and runs the update to ummm update the textarea with the update function 
// Note: remove() is OK in this case as #codebit1 is totally dynamically created 
updatefunction(); 
}); 

这里的问题是好的我可以删除/删除需要删除的位 - 因此“90%”,但我怎样才能摆脱“现在的孤儿”\n<br/>\n用于分隔#textarea中的2个div 。好吧,我可以在没有\n<br/>\n的情况下做到这一点,但它会让代码复制到“不整齐”的眼睛上,这就是为什么\n<br/>\n在那里的原因--也确保当代码被真正复制时,用户会得到合理的布局。

+1

您是否使用了正确的文档类型? – 2011-02-11 11:59:20

+0

@Timo我正要问同样的事情...... – 2011-02-11 12:03:28

回答

1

我在想你在做什么是不正确的。

A <textarea>是一个多行输入对象。所以,你不想使用$('#textarea').html()函数(我认为它不存在<textarea>),但你想用$('#textarea').val()函数来更新它的内容。

如果你做$('#textarea').val('this is the <br />html to copy'),你会得到正确的结果。

另一方面,您确实想要使用.html()而不是.val()作为$('#populationhold')对象,因为您正在检索它的值并且它是子级。

关于innerHTML的和XHTML

XHTML和innerHTML的是没有朋友。他们只是不一起工作。如果您将文档作为xhtml/xml提供,那么您将遇到麻烦。它没有意义,XML中的innerHTML。

<element>value 
<child>childvalue</child> 
</element> 

innerHTML的仅仅是得到元素的值的函数,然后concatinates这是儿童的名字和值......这只是一些字符串操作。

半解

史蒂夫·塔克创建innerXHTML功能。你可以看到它在这里工作:

http://jsfiddle.net/pYUD4/10/

有,但是,有一件事你<br />转换为<br></br>,但是但是,就我而言,这是有效的XHTML。我会尝试编写一个能够很好地完成这项工作的函数,因为现在似乎没有办法做到这一点。但这可能需要一段时间xD