点击触发按钮不工作阅读更多和阅读更少的按钮

时间:2017-09-26 05:35:22

标签: javascript jquery html css

我正在尝试更多阅读并阅读更少的按钮。一切都很有效,我总共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>

1 个答案:

答案 0 :(得分:2)

问题出在var button = $(".actionButton");,您应该选择.actionButton内的element

var button = element.find(".actionButton");