我的问题就像在stackoverflow中重复一样;我仍然没有找到任何最终解决方案。 如果div包含的字符大于300,我想显示 readmore 选项。再次单击 readmore 后,将显示其余内容。
我通过搜索Google尝试了一些操作,请忽略我的代码并帮助我修复它。
HTML代码:
<div class="only-so-big" id="shw">
This one has way too much content to show. Best be saving it for those who want to read everything in here.
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia
voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi THE END!
</div>
脚本代码:
<script type="text/javascript">
var str = $('#shw').text();
if(len>300){
var new_str = str.subtstr(0,300);
new_str += '<div data="'+str+'">' + new_str + '... </div>';
var newDiv = $(new_str);
var link_read_more = $('<a class="read_more">Read more</a>');
link_read_more.click(function(){
var originaltext = $(this).parent().attr('data');
$(this).parent().html(originaltext);
});
newDiv.append(link_read_more);
}
</script>
答案 0 :(得分:0)
尝试一下:
$(document).ready(function() {
var str = $('#shw').text();
if (str.length > 300) {
$('#shw').empty().html(str.substr(0,300));
var moreLink = '<a href="#" class="read_more">Read more</a>';
$('#shw').append(moreLink);
$('.read_more').on('click', function(e) {
e.preventDefault();
$('#shw').empty().html(str);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="only-so-big" id="shw">
This one has way too much content to show. Best be saving it for those who want to read everything in here.
Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia
voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi THE END!
</div>