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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:31:57  来源:igfitidea点击:

How to get the wrapper element created with "wrapAll()"?

javascriptjquerywrapall

提问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 .wrapperelements in the DOM, so this won't work:

注意:.wrapperDOM 中还有其他元素,所以这不起作用:

$(".wrapper").css("border", "5px solid black");

I don't want to give a unique idto the created wrapper either.

我也不想给id创建的包装器一个独特的。

回答by Frédéric Hamidi

Since you just wrapped the elements, you can use parent()to obtain the newly inserted wrappers:

由于您刚刚包装了元素,您可以使用parent()来获取新插入的包装器:

$(".a").wrapAll("<div class='wrapper'></div>")
       .parent().css("border", "5px solid black");

回答by karim79

The jQuery object stored in wrappergets cloned when wrapAllgets called, so you cannot affect the .wrapperswhich have been inserted into the DOM by manipulating wrapper, you need to select them from the document.

存储在其中的 jQuery 对象在wrapperwrapAll调用时会被克隆,因此您无法.wrappers通过操作来影响已插入 DOM 的对象wrapper,您需要从文档中选择它们。

回答by Billy Moon

$(function() {
    var wrapper = $("<div class='wrapper'></div>");
    var wrapped = $(".a").wrapAll(wrapper);
    wrapped.css("border", "5px solid black");
});