【发布时间】:2017-09-18 12:45:23
【问题描述】:
我在 cmets 上使用 show more/show less。目的显然是缩短和延长用户单击 jquery 的创建链接时创建的 cmets。
我遇到的问题是我有多个 cmets,而不是 jquery 代码对从数据库带回的每个评论执行显示更多/更少功能,它只对从数据库带来的第一条评论执行此操作,然后复制自身并覆盖其他图像。
这段代码有什么问题,解决方法是什么? html/php:
<p class="product-comment">$comments->comment</p>
jQuery
$(document).ready(function(){
var showmoreHtml = $(".product-comment").html();
var showlessHtml = showmoreHtml.substr(0,400);
if(showmoreHtml.length > 400){
$(".product-comment").html(showlessHtml).append("<a href='' class='product-comment-more'> (...Show More)</a>");
}else{
$(".product-comment").html(showmoreHtml);
}
$("body").on("click", ".product-comment-more", function(event){
event.preventDefault();
$(this).parent(".product-comment").html(showmoreHtml).append("<a href='' class='product-comment-less'> (Show less)</a>")
});
$("body").on("click", ".product-comment-less", function(event){
event.preventDefault();
$(this).parent(".product-comment").html(showmoreHtml.substr(0,400)).append("<a href='' class='product-comment-more'> (...Show More)</a>")
});
});
【问题讨论】:
-
你应该使用每个函数,这里有一些文档api.jquery.com/jquery.each
-
问题是您使用的选择器会返回多个项目。当您有多个项目时,jQuery 函数的工作方式会有所不同,具体取决于函数 - 例如,
.html()将获取第一个元素的 html,而.html(text)将为所有元素设置 html。最简单的选择是有两个 div,一个是长的,一个是短的,然后切换它们。
标签: javascript jquery