为什么在Jquery appendTo中不能很好地在Textarea上运行?



我想在textarea中附加一些html代码(只是语法,就像字符串一样(。我不知道原因,但是我的代码效果不佳,实际上,如果我运行代码并且按下按钮,请按照html代码正确地附加到文本方面,但是如果我在文本方面写东西,并且在我尝试之后要单击或重新单击按钮以附加HTML代码,什么也不会发生!在这里我的测试小提琴:
https://jsfiddle.net/jklh0wat/1/
我还使用django,在我的情况下,textarea是由django form给出的(以我使用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>

问题是因为您的语法不正确。您无法可靠地将任何内容附加到textarea。相反,您需要使用val()设置元素的value。您可以通过将函数传递到jQuery的val()方法来达到与附加值相同的效果,例如:

$("#link").on('click', function() {
  $('#desc').val(function(i, v) {
    return v + '<a href="link">titolo-link</a>';
  });
});
#desc {
  width: 350px;
  height: 200px;
  border: 1px solid
}
<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://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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"><b>hello</b></textarea>

还要注意,我删除了内联风格,因为它们不是很好的做法。

我必须使用:onclick="insertAtCaret('desc', '<b>hi</b>')"在这种情况下,所有内容都可以使用商品,但是当我将类似的" titolo-link"放置时,引号将成为一个错误!

在这种情况下,您可以使用/逃脱引号,但是,就像我上面所做的那样,最好使用不引人注目的事件处理程序。尝试以下操作:

$('#link').on('click', function() {
  insertAtCaret('desc', '<a href="link">titolo-link</a>');
}); 

相关内容

最新更新