在div editable中添加动态创建的元素

时间:2018-03-08 15:27:35

标签: javascript jquery html5

我想在div中添加动态创建的元素(<a>)而不删除其内容。

当我将没有内容的元素插入到可编辑的div中时,它可以工作,但这不是我想要的。

&#13;
&#13;
var link = document.createElement('a');
var linkText = document.createTextNode('Test');
link.appendChild(linkText);
link.setAttribute('data-id', 1);
link.setAttribute('data-type', 12);
  link.href  = 'wwww.google.com';
  // this is ok 
  $('#editable').html(link);
 // but when inserting the old html  is not ok 
$('#editable').html($('#editable').html() + link);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message" required="required" name="editable" id="editable" data-editable="true" contenteditable="true">Add request ...</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

为什么不完全使用jQuery:

$(function() {
  $('<a/>')
    .attr({
      'data-id': 1,
      'data-type': 12,
      'href': 'http://www.google.com' })
    .text('Test')
    .appendTo( $('#editable') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message" required="required" name="editable" id="editable" data-editable="true" contenteditable="true">Add request ...</div>

答案 1 :(得分:1)

您可以使用append

&#13;
&#13;
var link = document.createElement('a');
var linkText = document.createTextNode('Test');
link.appendChild(linkText);
link.setAttribute('data-id', 1);
link.setAttribute('data-type', 12);
link.href = 'wwww.google.com';
$('#editable').append(link);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="message" required="required" name="editable" id="editable" data-editable="true" contenteditable="true">Add request ...</div>
&#13;
&#13;
&#13;