jQuery使用insertAfter创建的元素不起作用

时间:2018-12-06 17:53:31

标签: javascript jquery dom

页面上有几个div类为“ wrap-me”的div。

我想在“ wrap-me”之后添加一个元素“ add-me”,并将两者分别包裹在“ wrapper-inner”和“ wrapper”中。

基本上-它看起来应该像这样:

<div class="wrapper">
    <div class="wrapper-inner">
        <div class="wrap-me"></div>
        <div class="add-me"></div> 
    </div>
</div>

这是我的实现方式

const $addMe = $("<div>", { class: "add-me" });
const $wrapper = $('<div>', { class: "wrapper" });
const $wrapperInner = $('<div>', { class: "wrapper-inner" });

$.each($(".wrap-me"), (i, wrapMe) => {
    const $wrapMe = $(wrapMe);

    $wrapMe.wrap($wrapper).wrap($wrapperInner);
    $addMe.insertAfter($wrapMe);
});

以下是输出:

<div class="wrapper">
    <div class="wrapper-inner">
        <div class="wrap-me"></div>
    </div>
</div>

几乎到了,唯一的事情是“ add-me”没有插入到DOM中。怎么了?

1 个答案:

答案 0 :(得分:1)

//get the template
var wrapperTemplate = $('#wrapperTemplate').text();

$('.wrap-me').each(function(index, element){
  //create a new element to put in the DOM
  var $wrapper = $(wrapperTemplate);
  
  //put the wrapper after the element we are going to replace
  $wrapper.insertAfter(element);
  //move the element into the wrapper where it should be
  $wrapper.find('.wrapper-inner').prepend(element);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap-me">A</div>
<div class="wrap-me">B</div>
<div class="wrap-me">C</div>
<div class="wrap-me">D</div>

<!-- HTML template for what we want to add, so it's not in the javascript -->
<script type="text/html" id="wrapperTemplate">
  <div class="wrapper">
      <div class="wrapper-inner">
          <div class="add-me"></div> 
      </div>
  </div>
</script>