Uncaught HierarchyRequestError: Failed to execute 'insertBefore' on 'Node': The new child element contains the parent.
当窗口宽度小于 767 时,我只是尝试在 span3
之前附加 span9
并且出现此错误,这是为什么?
$(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
类元素 inside 类为 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>
关于javascript - 未捕获的层次结构请求错误 : Failed to execute 'insertBefore' on 'Node' : The new child element contains the parent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37652097/