jQuery如何在THIS

时间:2018-06-24 10:18:03

标签: jquery

如何在btn之前添加新的div?

我尝试过:

element.parent("div").append(data);

但是它在按钮之后添加了新数据,我希望它位于按钮上方(以及其余的div之后)

<div>

  <div id="1"></div>
  <div id="2"></div>
  <div id="3"></div>

  <a href="#" class="new_sec-btn" data-itinID="2">New Section</a>
</div>

1 个答案:

答案 0 :(得分:0)

使用insertBefore()函数在目标之前的匹配元素集中插入元素。

$('.new_sec-btn').on('click', function(){
  data = `<div>"Lorem ipsum dolor sit amet, consectetur   adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</div>`;

  $( data ).insertBefore( ".new_sec-btn" );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>

  <div id="1"></div>
  <div id="2"></div>
  <div id="3"></div>

  <a href="#" class="new_sec-btn" data-itinID="2">New Section</a>
</div>