简体   繁体   English

无法附加到jQuery包装

[英]can't append to jQuery wrap

Why can't you append to an element that you use to wrap another - see example below? 为什么不能附加到用于包装另一个元素的元素 - 请参阅下面的示例?

 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); 
 <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> 

wrap() seems to clone the markup of the provided element for wrapping, not the actual element itself. wrap()似乎克隆了提供的包装元素的标记,而不是实际的元素本身。 You can see it in the developer tools when you use console.log($testWrapper) and hover over that line in your browser console: normally, the DOM element should be highlighted, but it's not. 当您使用console.log($testWrapper)并将鼠标悬停在浏览器控制台中的那一行时,您可以在开发人员工具中看到它:通常,DOM元素应该突出显示,但事实并非如此。 So what is referenced by the variable $testWrapper after wrapping is still (a jQuery collection of) a node that is not attatched to the DOM. 因此,包装后变量$testWrapper所引用的内容仍然是(一个jQuery集合)一个未附加到DOM的节点。

 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! 
 <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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM