gpt4 book ai didi

javascript - 添加 JQuery "Read More"脚本而不剥离 HTML 标签

转载 作者:行者123 更新时间:2023-11-28 03:11:39 25 4
gpt4 key购买 nike

我正在将“阅读更多”链接脚本应用于 Rich HTML 字段,以便 chop 较长的副本 block 。下面是我正在使用的代码:

$(document).ready(function(){
var maxLength = 300;
$(".show-read-more").each(function(){
var myStr = $(this).text();
if($.trim(myStr).length > maxLength){
var newStr = myStr.substring(0, maxLength);
var removedStr = myStr.substring(maxLength, $.trim(myStr).length);
$(this).empty().html(newStr);
$(this).append(' <a href="javascript:void(0);" class="read-more">read more...</a>');
$(this).append('<span class="more-text">' + removedStr + '</span>');
}
});
$(".read-more").click(function(){
$(this).siblings(".more-text").contents().unwrap();
$(this).remove();
});
});

在我的模板中,我将字段流入应用了 show-read-more 类的 div,并且效果相当好。

使用示例如下:

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="utf-8">
<title>jQuery Add Read More Link</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function() {
var maxLength = 300;
$(".show-read-more").each(function() {
var myStr = $(this).text();
if ($.trim(myStr).length > maxLength) {
var newStr = myStr.substring(0, maxLength);
var removedStr = myStr.substring(maxLength, $.trim(myStr).length);
$(this).empty().html(newStr);
$(this).append(' <a href="javascript:void(0);" class="read-more">read more...</a>');
$(this).append('<span class="more-text">' + removedStr + '</span>');
}
});
$(".read-more").click(function() {
$(this).siblings(".more-text").contents().unwrap();
$(this).remove();
});
});
</script>
<style>
.show-read-more .more-text {
display: none;
}
</style>
</head>

<body>
<div class="show-read-more">
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>This is a very long paragraph...Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce efficitur massa id odio pharetra, in varius diam tincidunt. Nulla fringilla nunc lorem. In et elit id diam porttitor finibus vitae ut odio. Morbi sollicitudin
turpis non vulputate efficitur. Nulla rhoncus metus diam, porta consequat lacus scelerisque sed. Praesent et tempor mauris, non porttitor sapien. Pellentesque placerat ex non finibus gravida. Aenean at feugiat odio, sit amet ultricies diam. Integer
vehicula pulvinar leo, vel laoreet neque lacinia nec. Vestibulum nec cursus orci, vel dapibus risus. Nullam et tincidunt mauris. Nunc iaculis egestas purus in rhoncus. Donec a turpis quis libero rutrum.</p>
</div>
</body>

</html>

问题在于代码删除了所有 HTML 标签,使其成为一个大的未格式化段落。如何在不删除 HTML 的情况下实现同样的效果?

最佳答案

使用 .text() 将仅获取文本和 strip 标签,如果您希望获取所有子元素并将其放入变量中,请使用 .html();

var myStr = $(this).html();

example

关于javascript - 添加 JQuery "Read More"脚本而不剥离 HTML 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60045329/

25 4 0