无法附加到jQuery wrap

时间:2017-10-30 11:38:57

标签: javascript jquery

为什么不能附加到用于包装另一个元素的元素 - 请参阅下面的示例?



var $test = $('.test'),
    $test1 = $('.test1'),
    $move = $('.move'),
    $testWrapper = $('<div class="test-wrapper"></div>'),
    $test1Wrapper = $('<div class="test1-wrapper"></div>');


$test.wrap($testWrapper);
// move item and return to wrapper
$move.append($test);
$testWrapper.append($test); // this is the line that does not work?
console.log($testWrapper);   // still seems to be a jquery object?

$test1.after($test1Wrapper); // if you place the element after instead of using it to wrap, then it works?
$move.append($test1);
$test1Wrapper.append($test1);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">test</div>
<div class="test1">test 1</div>
<div class="move"></div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

wrap()似乎克隆了提供的包装元素的标记,而不是实际的元素本身。当您使用console.log($testWrapper)并将鼠标悬停在浏览器控制台中的那一行时,您可以在开发人员工具中看到它:通常,DOM元素应该突出显示,但事实并非如此。因此,包装后变量$testWrapper引用的内容仍然是(jQuery集合)一个未附加到DOM的节点。

&#13;
&#13;
var $test = $('.test'),
    $test1 = $('.test1'),
    $move = $('.move'),
    $testWrapper = $('<div class="test-wrapper"></div>');


$test.wrap($testWrapper);
// move item and return to wrapper
$move.append($test);
console.log($testWrapper); // <= if you hover this element in the browser console, it doesn't highlight the actual DOM element either; that's how you can visully detect that it's not the same element!
$testWrapper = $('.test-wrapper'); // select the actual DOM element that has been created for wrapping
$testWrapper.append($test); // now it will work!
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">test</div>
<div class="move"></div>
&#13;
&#13;
&#13;