我正在尝试制作“多读”和“少读”按钮。一切都很好,我总共有 4 个 div,其中字符受到限制,字符也受到限制,甚至按钮也工作正常,问题是按钮在某些 div 中工作,在某些 div 中不起作用,我不明白有什么问题吗?
function limitCharacters(){
$('.limit-characters').each(function(){
var element = $(this);
// var element = $('.limit-characters');
var elementHtml = element.html();
element.prepend(elementHtml);
element.find("p:first").addClass("limited");
element.find("p:last").addClass("unlimited hide-element");
var limitedElement = element.find('.limited');
var limitedElementString = limitedElement.text();
var subStringedString = limitedElementString.substring(0,500);
limitedElement.html(subStringedString);
var buttonElement = '<a href="#" class="btn btn-sample3 btn-sm actionButton ">Read More</a>';
element.append(buttonElement);
var button = $(".actionButton");
button.click(function(e){
$(this).parent().find(".unlimited").toggleClass("hide-element");
$(this).parent().find(".limited").toggleClass("hide-element");
$(this).toggleClass("read-less");
if($(this).hasClass("read-less")){
$(this).html("Read Less");
}else{
$(this).html("Read More");
}
e.preventDefault();
});
});
}
.hide-element{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="limit-characters">
<p>
Had best days of my life ever in Nepal. Wish you all a good time and hope to see you again in my next holiday and I promise to make longer holiday for best memories.Had best days of my life ever in Nepal. Wish you all a good time and hope to see you again in my next holiday and I promise to make longer holiday for best memories.Had best days of my life ever in Nepal. Wish you all a good time and hope to see you again in my next holiday and I promise to make longer holiday for best memories.Had best days of my life ever in Nepal. Wish you all a good time and hope to see you again in my next holiday and I promise to make longer holiday for best memories.
</p>
</div>
最佳答案
问题出在 var button = $(".actionButton");
中,您应该选择 element
内的 .actionButton
.
var button = element.find(".actionButton");
关于javascript - 单击触发按钮在“阅读更多”和“阅读更少”按钮中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46418531/