我有一个文本区域,正在填充 html
供人们剪切和粘贴的代码。该文本区域是使用 JQuery 和 .html()“填充”的。 “人口”来自 <div>
页面其他地方的示例:
“容纳“人口”的 Div
<div id="populationhold">this is the html to copy</div>
然后“JQ的魔法”“点击”按钮并填充文本区域
$('#button').click(function(){
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();
});
填充文本区域很好并且有效,“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
的原因在那里 - 还有\n<br/>\n
确实确保当实际复制代码时用户获得合理的布局。
最佳答案
我认为你所做的事情是不正确的。
一个<textarea>
是一个多行输入对象。所以,您不想使用$('#textarea').html()
函数(我认为它甚至不存在 <textarea>
),但您想使用 $('#textarea').val()
功能来更新其内容。
如果你这样做$('#textarea').val( 'this is the <br />html to copy')
,您将得到正确的结果。
另一方面,您确实想使用 .html()
而不是.val()
对于$('#populationhold')
对象,因为您正在检索它的值及其子对象。
关于innerHTML和XHTML
XHTML 和innerHTML 不是 friend 。他们只是不一起工作。如果您将文档作为 xhtml/xml 提供,那么您就会遇到麻烦。 XML 中的innerHTML 没有意义。
<element>value
<child>childvalue</child>
</element>
innerHTML 只是一个获取元素值的函数,然后连接它的子元素的名称和值...这只是一些字符串操作。
半解决方案
史蒂夫·塔克创建了一个innerXHTML功能。您可以在这里看到它的工作原理:
但是,您会得到一件事 <br />
翻译为<br></br>
,但是,就我而言,这是有效的 XHTML。我会尝试编写一个能够很好地完成这项工作的函数,因为现在似乎没有办法做到这一点。但这可能需要一些时间xD
关于JQuery .html() 打印准确的html代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4968389/