【发布时间】:2017-06-23 22:44:01
【问题描述】:
我想在 TextArea 中附加一些 html 代码(只是语法,如字符串)。我不知道原因,但我的代码不能正常工作,事实上,如果我运行代码并按下按钮,那么 html 代码将正确附加到 textarea 但如果我在 textarea 内写一些东西,然后我尝试单击或重新单击按钮以附加 html 代码没有任何反应!这是我的测试小提琴:
https://jsfiddle.net/jkLh0wat/1/
我也使用 Django,在我的情况下 textarea 是由 django 表单给出的(在表单中我使用 id “desc”到 textarea 字段)但我认为这不是 Django 问题,因为它是一个 html-jquery 问题...... .
这是代码:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button type="button" class="btn btn-info btn-xs" id="link">link</button>
<textarea id="desc" style="width:350px;height:200px;border:1px solid"><b>hello</b></textarea>
<script>
$("#link").on('click', function() {
$(document.createTextNode("<a href='link'>titolo-link</a>")).appendTo($("#desc"));
})
</script>
【问题讨论】:
-
into a textarea- 在文本区域内?因为你需要使用.val()来定位内部文本区域,append to将在文本区域结束后放置它 -
文本区域不能包含 HTML,只能包含文本。在 jQuery 中你不需要使用
createTextNode。一个简单的$("<a href='link'>titolo-link</a>")创建节点。但正如上面的评论所提到的,文本区域的内容是由它的 value 属性控制的。