在.wrap()和.unwrap()之间切换

时间:2019-07-09 03:27:45

标签: jquery unwrap wrapall

请查看代码演示以获取问题。

<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $('button').click(function () {
        $('p').wrapAll('<div class="container"></div>')
    });
});
</script>
<style type="text/css">
.container { background-color: yellow; padding: 10px; }
</style>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<button>Toggle button</button>
</body>
</html>

当我再次单击按钮时如何删除<div class="container"></div>,我知道.unwrap()可以删除,但是我不知道该怎么做?

提前谢谢!

3 个答案:

答案 0 :(得分:0)

2种方式:

首先是添加变量并切换:

$(document).ready(function(){
toggle = false;
    $('button').click(function () {
      if(!toggle){
        $('p').wrapAll('<div class="container"></div>');
      } else {
        $('p').unwrap();
      }
      toggle = !toggle;
    });
});
.container { background-color: yellow; padding: 10px; }
<script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>

<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<button>Toggle button</button>

第二个检测父对象是否包含div:

$(document).ready(function(){
    $('button').click(function () {
      if(!$('p').parent().is( "div" )){
        $('p').wrapAll('<div class="container"></div>');
      } else {
        $('p').unwrap();
      }
    });
});
.container { background-color: yellow; padding: 10px; }
<script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>

<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<p>This is a paragraph.</p>
<button>Toggle button</button>

答案 1 :(得分:0)

您可以设置计数器并检查自动换行,如下所示。

$(document).ready(function() {
  let wrap = true;
  $('button').click(function() {
    if (wrap) {
      $('p').wrapAll('<div class="container"></div>')
      wrap = false;
    } else {
      $("p").unwrap();
      wrap = true;
    }
  });
});
.container {
  background-color: yellow;
  padding: 10px;
}
<!DOCTYPE html>
<html>

<head>
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>

</head>

<body>
  <p>This is a paragraph.</p>
  <p>This is a paragraph.</p>
  <p>This is a paragraph.</p>
  <button>Toggle button</button>
</body>

</html>

答案 2 :(得分:0)

您可以简单地使用toggleClass()。希望对您有帮助

$(document).ready(function(){
    $('button').click(function () {
        $('#wrapper').toggleClass('container')
    });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>
<style type="text/css">
.container { background-color: yellow; padding: 10px; }
</style>
</head>
<body>
  <div id="wrapper">
    <p>This is a paragraph.</p>
    <p>This is a paragraph.</p>
    <p>This is a paragraph.</p>
    <button>Toggle button</button>
  </div>
</body>
</html>