Uncaught HierarchyRequestError:无法在'Node'上执行'insertBefore':新的子元素包含父元素

时间:2016-06-06 07:47:28

标签: javascript jquery

  

Uncaught HierarchyRequestError:无法在'Node'上执行'insertBefore':新的子元素包含父元素。

当窗口宽度小于767时,我只是尝试在span9之前附加span3并且我有这个错误,为什么会这样?

enter image description here

$(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>

1 个答案:

答案 0 :(得分:1)

虽然您显示的内容不会出现错误,但错误信息非常明确:显然,您至少有一个元素span3 in 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>