javascript 使用 jQuery 在其他两个 div 周围创建包装 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7081269/
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:54:27  来源:igfitidea点击:

Create wrapper div around two other divs with jQuery

javascriptjqueryhtml

提问by riskogab

How can I add an div element around 2 (or more) div? What I think:

如何在 2 个(或更多)div 周围添加 div 元素?我的想法:

$('div.list-price').each(function() {
  $(this).before('<div class="action-price">');
  $(this).next().after('</div>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-price">20000</div>
<div class="sell-price">10000</div>

I hoped that above code will do this:

我希望上面的代码可以做到这一点:

<div class="action-price">
  <div class="list-price">20000</div>
  <div class="sell-price">10000</div>
</div>

But:

但:

<div class="action-price"></div>
<div class="list-price">20000</div>
<div class="sell-price">10000</div>

Can anybody help me?

有谁能够帮我?

采纳答案by Guffa

You are thinking of the elements as HTML code, but they are objects. You can't add the starting and ending tag separately, because they are not complete elements.

您将元素视为 HTML 代码,但它们是对象。您不能单独添加开始和结束标记,因为它们不是完整的元素。

Add the new element, and move the existing divs inside it:

添加新元素,并将现有的 div 移动到其中:

$('div.list-price').each(function() {
  var newDiv = $('<div/>').addClass('action-price');
  $(this).before(newDiv);
  var next = $(this).next();
  newDiv.append(this).append(next);
});

Demo: http://jsfiddle.net/Guffa/eFXbN/1/

演示:http: //jsfiddle.net/Guffa/eFXbN/1/

回答by DLL

Try using the wrapAll function:

尝试使用 wrapAll 函数:

$('.list-price, .sell-price').wrapAll('<div class="action-price" />');

回答by Blowsie

A nice approach to this is to do the following.

一个很好的方法是执行以下操作。

$("div.list-price").each(function(){
     $(this).nextUntil("div.list-price").andSelf().wrapAll("<div class='action-price'></div>");
});

Its simple and readable, probably the way the jQuery devs intended it to be written.

它简单易读,可能是 jQuery 开发人员希望编写的方式。

回答by Guard

$first = ... // the 1st element
$rest = ... // other elements, may be just the second one
$first.wrap('<div class="wrapper"/>').parent().append($rest)

回答by Eric

I had to revese your last line to:

我不得不修改你的最后一行:

$rest.wrap('').parent().append($first);

$rest.wrap('').parent().append($first);