【问题标题】:Stripping off all p tags inside a div when the div loads加载 div 时剥离 div 内的所有 p 标签
【发布时间】:2018-03-19 12:19:23
【问题描述】:

这段代码有什么问题? 我希望当 div 加载所有 -p- 标签时 div "story_L3" 被删除,留下纯文本。很简单,但我的代码不起作用,请指教(见示例)

<div id="story_L3">
  <p class="one">This is a paragraph inside a p element.</p>
  <p class="two">This is a paragraph inside another p element.</p>
</div>


.one{background-color: yellow;}
.two{background-color: pink;}


$('#story_L3').load(function(){
    $('#story_L3').find('p').contents().unwrap(); 
});

我也试过了:

$('#story_L3').load(function(){
    ($('#story_L3 > p').contents().unwrap(); 
});

和:

$('#story_L3').load(function(){
      if($('#story_L3').find('p').length !== 0){
          $('p').contents().unwrap();     
        }
     });

【问题讨论】:

  • 用 document.ready 函数代替 div.load 试试
  • 可以直接使用ready函数

标签: jquery unwrap


【解决方案1】:

你不需要使用.load(),直接在document-ready handler中使用.unwrap()代码

$('#story_L3 p').contents().unwrap();
.one {
  background-color: yellow;
}

.two {
  background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="story_L3">
  <p class="one">This is a paragraph inside a p element.</p>
  <p class="two">This is a paragraph inside another p element.</p>
</div>

【讨论】:

    【解决方案2】:

    试试这个:

    $(document).ready(function () {
                    $("#story_L3 > p").contents().unwrap();
                });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="story_L3">
            <p class="one">This is a paragraph inside a p element.</p>
            <p class="two">This is a paragraph inside another p element.</p>
        </div>

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 2021-10-25
      • 2013-05-05
      • 1970-01-01
      • 2016-08-03
      • 2011-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多