当div加载时,剥离div内的所有p标签

时间:2018-03-19 12:19:24

标签: jquery unwrap

这段代码有什么问题? 当div加载div中的所有-p-标签时,我想要这样#story; 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();     
        }
     });

2 个答案:

答案 0 :(得分:1)

您不需要使用.load(),直接在文档就绪处理程序中使用.unwrap()代码

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

.two {
  background-color: pink;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:

$(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>