我正在使用 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/