javascript 如何获取使用“wrapAll()”创建的包装元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6972824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the wrapper element created with "wrapAll()"?
提问by Misha Moroshko
Consider the following code: (live example here)
考虑以下代码:(此处为现场示例)
$(function() {
var wrapper = $("<div class='wrapper'></div>");
$(".a").wrapAll(wrapper);
wrapper.css("border", "5px solid black"); // Doesn't work
});
.wrapper {
background-color: #777;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a">Hello</div>
<div class="a">Stack</div>
<div class="a">Overflow</div>
What would be the right way to get the created wrapper and change its attributes ?
获取创建的包装器并更改其属性的正确方法是什么?
Note:There are other .wrapper
elements in the DOM, so this won't work:
注意:.wrapper
DOM 中还有其他元素,所以这不起作用:
$(".wrapper").css("border", "5px solid black");
I don't want to give a unique id
to the created wrapper either.
我也不想给id
创建的包装器一个独特的。
回答by Frédéric Hamidi
回答by karim79
The jQuery object stored in wrapper
gets cloned when wrapAll
gets called, so you cannot affect the .wrappers
which have been inserted into the DOM by manipulating wrapper
, you need to select them from the document.
存储在其中的 jQuery 对象在wrapper
被wrapAll
调用时会被克隆,因此您无法.wrappers
通过操作来影响已插入 DOM 的对象wrapper
,您需要从文档中选择它们。
回答by Billy Moon
$(function() {
var wrapper = $("<div class='wrapper'></div>");
var wrapped = $(".a").wrapAll(wrapper);
wrapped.css("border", "5px solid black");
});