首页 > 解决方案 > jQuery / 删除

不丢失超链接或阅读更多内容位于文本下方

问题描述

将“阅读更多”保留在文本旁边并从 var content = $(".myClass p").html(); 中删除“p”的任何想法 不丢失超链接?非常感谢..

      var show_char = 280;
      var ellipses = "... ";
      var content = $(".myClass").html();
      if (content.length > show_char) {
         var a = content.substr(0, show_char);
         var b = content.substr(show_char - content.length);

         var html = a + "<span class=\'abc\'>" + ellipses + "</span><span class=\'abc\' style=\'display:none\'>" + b + "</span><a class=\'read-more\' href=\'#\'>Read more</a>";        
        $(".myClass").html(html);
      }
      $(".read-more").click(function(e) {
         e.preventDefault();
         $(".read-more").text() == "Read more" ? $(".read-more").text(" Read less") : $(".read-more").text("Read more");     
         $(".myClass .abc").toggle();
      });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="myClass">
  <p><a href="https://stackoverflow.com/">stackoverflow</a> is a question and answer site for professional and enthusiast programmers. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange.</p>
</div>

标签: jquery

解决方案


只需要做一件小事,这应该可以正常工作。您可以包含子组合器 ( > ) 以在其中捕获p标签,.myClass同时省略在第三行中写入标签,即var content = $(".myClass").html();
我希望这会有所帮助!如果它有助于解决您的问题,请随时通过单击此答案左侧的 ✓ 将答案标记为已接受

var show_char = 280;
      var ellipses = "... ";
      var content = $(".myClass >*").html(); 
      
      if (content.length > show_char) {
        var a = content.substr(0, show_char);
        var b = content.substr(show_char - content.length);
        var html = a + "<span class=\'abc\'>" + ellipses + "</span><span class=\'abc\' style=\'display:none\'>" + b + "</span><a class=\'read-more\' href=\'#\'>Read more</a>";
        $(".myClass").html(html);
      }
      $(".read-more").click(function(e) {
         e.preventDefault();
         $(".read-more").text() == "Read more" ? $(".read-more").text(" Read less") : $(".read-more").text("Read more");     
         $(".myClass .abc").toggle();
      });
html {
  font-size: 18px;
  font-family: sans-serif
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="myClass">
  <p><a href="https://stackoverflow.com/">stackoverflow</a> is a question and answer site for professional and enthusiast programmers. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange.</p>
</div>


推荐阅读