为什么追加jquery无法正常工作?

时间:2018-01-22 11:56:08

标签: jquery html html5 append

我想使用jquery append函数附加HTML代码,但它无效。

我想使用此jquery代码附加 </div><div class="item">

$(this).before('</div> <div class="item">');

但它追加<div class="item"></div> 建议我任何最佳解决方案。

1 个答案:

答案 0 :(得分:2)

DOM是对象的树结构,而不是HTML之类的文本。如果你想将div的内容分成两部分,你不能只是插入标记来做到这一点,你必须创建一个新的div并将子节点从原始节点移动到你的想要感动。

例如,如果您希望将该代码中this之前的所有内容移动到新的div:

// Create an insert the div
var div = $("<div></div>").addClass("item");
div.insertBefore(this);
// Move `this` and all following siblings into it
var $this = $(this);
div.append($this.add($this.nextAll()));

(有更简洁的方法可以做到这一点,但它们并不像初学者那么清楚。)

直播示例:

&#13;
&#13;
$(".item").on("click", "div", function() {
    // Create an insert the div
    var div = $("<div></div>").addClass("item");
    div.insertBefore(this);
    // Move `this` and all following siblings into it
    var $this = $(this);
    div.append($this.add($this.nextAll()));
});
&#13;
.item {
  border: 1px solid #ddd;
}
&#13;
<p>Click a line below to move it and the ones following it into a new div:</p>
<div class="item">
  <div>Line 1</div>
  <div>Line 2</div>
  <div>Line 3</div>
  <div>Line 4</div>
  <div>Line 5</div>
  <div>Line 6</div>
  <div>Line 7</div>
  <div>Line 8</div>
  <div>Line 9</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;