当Windows宽度小于767时,我只是尝试在span9之前附加span3,并且出现此错误,这是为什么?

javascript - 未捕获的HierarchyRequestError : Failed to execute  'insertBefore'  on  'Node' : The new child element contains the parent-LMLPHP

$(document).ready(function() {
  // Optimalisation: Store the references outside the event handler:
  var $window = $(window);
  var $content = $('.content');
  var $cats = $('.span3');

  function checkWidth() {
      var windowsize = $window.width();
      if (windowsize < 767) {
        $content.insertBefore($cats);
      } else if (windowsize > 767) {
        $content.insertAfter($cats);
      }
    }
    // Execute on load
  checkWidth();
  // Bind event listener
  $(window).resize(checkWidth);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="content-entry">
  <div class="row">
    <div class="span3">span3</div>
    <div class="span9 content">span9/content</div>
  </div>
</div>

最佳答案

尽管所显示的错误并未发生,但错误消息却很清楚:显然,在类span3的元素内部至少有一个元素与content相像,如下所示:

$(document).ready(function() {
  // Optimalisation: Store the references outside the event handler:
  var $window = $(window);
  var $content = $('.content');
  var $cats = $('.span3');

  function checkWidth() {
      var windowsize = $window.width();
      if (windowsize < 767) {
        $content.insertBefore($cats);
      } else if (windowsize > 767) {
        $content.insertAfter($cats);
      }
    }
    // Execute on load
  checkWidth();
  // Bind event listener
  $(window).resize(checkWidth);
});
<div class=".content-entry">
  <div class="row">
    <div class="content"><!-- Note this new element -->
        <div class="span3">span3</div>
    </div>
    <div class="span9 content">span9</div>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>


解决方案是将选择器更仔细地针对要移动的元素。显然content和/或span3用于其他用途以及您在此处使用的用途。

例如:

$(document).ready(function() {
  // Optimalisation: Store the references outside the event handler:
  var $window = $(window);
  var $content = $('.move-this');     // Changed the class
  var $cats = $('.relative-to-this'); // Changed the class

  function checkWidth() {
      var windowsize = $window.width();
      if (windowsize < 767) {
        $content.insertBefore($cats);
      } else if (windowsize > 767) {
        $content.insertAfter($cats);
      }
    }
    // Execute on load
  checkWidth();
  // Bind event listener
  $(window).resize(checkWidth);
});
<div class=".content-entry">
  <div class="row">
    <div class="content"><!-- Note this new element -->
        <div class="span3 relative-to-this">span3</div><!-- Added a class -->
    </div>
    <div class="span9 content move-this">span9</div><!-- Added a class -->
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

10-06 15:48