javascript - 在 WooCommerce 存档产品类别描述上添加“阅读更多/阅读更少”按钮

标签 javascript html jquery wordpress woocommerce

我正在使用 JS 在 WooCommerce 存档产品类别描述上创建“阅读更多”按钮/“阅读更少”按钮。将部分文本隐藏到阅读更多可扩展 div 中

“阅读更多”按钮正在工作,“阅读更少”按钮正在工作,但在“阅读更多”和“阅读更少”按钮事件/功能各单击一次后,它停止工作:

jQuery( function( $ ) {
    $(document).ready(function() {
        //Get the current height of the description container
        let curHeight = $(".archive-description").height();

        //Set the height of the description container
        $(".archive-description").css({
            "height": "80px", 
            "overflow": "none",
        });

        //Add 'Read more button
        $(".archive-description").after( "<button class='read-more'>Read more...</button>" );

        //Set description container back to its original height
        $( ".read-more" ).on( "click", function() {
            $(".archive-description").animate({height: curHeight});
            $('.read-more').hide();
            $(".archive-description").after( "<button class='read-less'>Read less...</button>" );
        });
    });
    
    $(document).on('click', '.read-less', function () {
        $(".archive-description").animate({height: 80});
        $('.read-less').hide();
        $(".archive-description").after( "<button class='read-more'>Read more...</button>" );
    });
});

最佳答案

一旦单击“阅读更多”或“阅读更少”,它们就会由 jQuery 代码动态重新生成。

所以现在它们不是初始渲染 DOM 的一部分。要解决这些问题,您需要使用 .on 处理程序。

所以像这样转换:

$(document).on( "click",".read-more", function() {
    $(".archive-description").animate({height: curHeight});
    $('.read-more').hide();
    $(".archive-description").after( "<button class='read-less'>Read less...</button>" );
});

关于javascript - 在 WooCommerce 存档产品类别描述上添加“阅读更多/阅读更少”按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77057009/

相关文章:

php - googlemaps 文档类型错误

javascript - 如何使用 PhoneGap Javascript 在 android 中读取文件

javascript - 如何防止 TextMate 出现 "matching"//commented {( 括号(在 Javascript 中)?

javascript - 执行 WebSocket/AJAX 应用程序的 'soft-refresh'(仅 JS 和 CSS)

javascript - 即使底部不在 View 中,也使水平滚动条始终可见

jquery - 在 jQuery 中切换元素样式的最佳、最快的方法是什么?

javascript - 使用 dojo 更改 <div> 的 CSS 类

JavaScript。图像翻转

javascript - offset() 在移动浏览器中返回不同的值

javascript - 如何从 jQuery 动态无延迟地加载 div 中的图像?