【问题标题】:Show read more link if the text exceeds a certain length using jQuery如果使用 jQuery 的文本超过一定长度,则显示阅读更多链接
【发布时间】:2018-11-12 14:24:58
【问题描述】:

我想在文章描述的 100 个字之后添加“显示更多”和“显示更少”功能:在此页面中 http://devo.cutwatches.com/en/component/spsimpleportfolio/item/3-powerfull

我用过这个鳕鱼,但它不起作用,它给出了 Uncaught TypeError: $ is not a function

        <p class="show-read-more">
        <?php echo $this->item->description; ?>  </p>

和

  <script type="text/javascript">
$(document).ready(function(){
var maxLength = 300;
$(".show-read-more").each(function(){
    var myStr = $(this).text();
    if($.trim(myStr).length > maxLength){
        var newStr = myStr.substring(0, maxLength);
        var removedStr = myStr.substring(maxLength, $.trim(myStr).length);
        $(this).empty().html(newStr);
        $(this).append(' <a href="javascript:void(0);" class="read- 
   more">read more...</a>');
        $(this).append('<span class="more-text">' + removedStr + '</span>');
    }
});
    $(".read-more").click(function(){
    $(this).siblings(".more-text").contents().unwrap();
    $(this).remove();
});
});
</script>


<style type="text/css">
    .show-read-more .more-text{
    display: none;
}

`

我用 css 试过了,但是不行

请问我该如何解决?

【问题讨论】:

  • 您的页面中包含 jquery 吗?如果是,请将其包含在问题中提到的 script 标签之前的 head 中,并在结束 body 标签之前保留 script 标签
  • 我也使用 joomla 并且 jquery 已经添加,当我再次添加时页面不再加载..
  • 如果添加了jquery就不要再添加了,只需要在body结束标签之前保留script标签

标签: javascript php html css


【解决方案1】:

你的html应该是这样的

<html>
  <head>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  </head>
  <body>

  // Body

  <script type="text/javascript">
    $(document).ready(function(){
    var maxLength = 300;
    $(".show-read-more").each(function(){
        var myStr = $(this).text();
        if($.trim(myStr).length > maxLength){
            var newStr = myStr.substring(0, maxLength)  ;
            var removedStr = myStr.substring(maxLength, 
            $.trim(myStr).length);
            $(this).empty().html(newStr);
            $(this).append(' <a href="javascript:void(0);" class="read- 
   more">read more...</a>');
            $(this).append('<span class="more-text">' + removedStr + '</span>');
    }
});
    $(".read-more").click(function(){
    $(this).siblings(".more-text").contents().unwrap();
    $(this).remove();
});
});
</script>

 </body>
</html>

【讨论】:

猜你喜欢
  • 2022-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-24
  • 2022-01-09
  • 1970-01-01
  • 1970-01-01
  • 2012-08-26
相关资源
最近更新 更多