我正在为jQuery中的文本设置更多/更少的按钮。当我的jQuery脚本加载时,我想只显示div中的一些文本。在这种情况下,任何文字>我想先隐藏650个字符。单击按钮后,将显示所有文本。再次单击时,文本将压缩为原始的部分隐藏大小。我无法弄清楚如何为每个类迭代单独运行jQuery函数。截至目前,两个类文本都被第一个DIV中的文本替换。我需要一次将函数范围限制为一个类。
有什么建议吗?
这是一个详细说明问题的小提琴 - https://jsfiddle.net/carbot3000/q6k8yr9o/40/
这是我所指的功能 -
jQuery('.reviewbody').each(function() {
console.log(h);
if (rvwbody.length > showChar) {
jQuery(".btnMore").show();
jQuery(this).html(c);
console.log(c);
答案 0 :(得分:0)
好的,这是一个有效的例子:
jQuery(document).ready(function() {
var showChar = 50; // How many characters are shown by default
var ellipsestext = "...";
jQuery('.reviewbody').each(function() {
var rvwElem = jQuery(this);
var fullVal = rvwElem.html();
var truncatedVal = fullVal.substr(0, showChar);
console.log(fullVal);
if (fullVal.length > showChar) {
debugger;
$(rvwElem).next(".btnMore").first().show().on('click', function() {
jQuery(this).html(jQuery(this).text() == 'View Less' ? 'View More' : 'View Less');
jQuery(".home_testimonial_section .home_testimonial_slider_wrap").toggleClass("rvwHeight");
$(rvwElem).html($(rvwElem).html() == truncatedVal ? fullVal : truncatedVal);
console.log(fullVal);
});
}
// You still want to show the content if it is shorter than "showChar"
$(rvwElem).html(truncatedVal);
console.log(truncatedVal);
});
});

.morecontent span {
display: none;
}
.morelink {
display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="home_testimonial_slider_wrap">
<div class="mySlides w3-animate-fading">
</div>
<div class="reviewbody">12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing12345testing
</div>
<button class="btnMore" style="display:none;">View More</button>
<div class="mySlides w3-animate-fading">
</div>
<div class="reviewbody"> 6789testing6789testing67896789testing6789testing67896789testing6789testing67896789testing6789testing67896789testing6789testing67896789testing6789testing67896789testing6789testing67896789testing6789testing67896789testing6789testing67896789testing6789testing67896789testing6789testing67896789testing6789testing67896789testing6789testing6789testing6789testing6789testing6789testing6789testing6789
</div>
<button class="btnMore" style="display:none;">View More</button>
</div>
&#13;
这里改变了主要内容: