jquery - jQuery / 删除
不丢失超链接或阅读更多内容位于文本下方
问题描述
将“阅读更多”保留在文本旁边并从 var content = $(".myClass p").html(); 中删除“p”的任何想法 不丢失超链接?非常感谢..
var show_char = 280;
var ellipses = "... ";
var content = $(".myClass").html();
if (content.length > show_char) {
var a = content.substr(0, show_char);
var b = content.substr(show_char - content.length);
var html = a + "<span class=\'abc\'>" + ellipses + "</span><span class=\'abc\' style=\'display:none\'>" + b + "</span><a class=\'read-more\' href=\'#\'>Read more</a>";
$(".myClass").html(html);
}
$(".read-more").click(function(e) {
e.preventDefault();
$(".read-more").text() == "Read more" ? $(".read-more").text(" Read less") : $(".read-more").text("Read more");
$(".myClass .abc").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myClass">
<p><a href="https://stackoverflow.com/">stackoverflow</a> is a question and answer site for professional and enthusiast programmers. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange.</p>
</div>
解决方案
只需要做一件小事,这应该可以正常工作。您可以包含子组合器 ( > ) 以在其中捕获p
标签,.myClass
同时省略在第三行中写入标签,即var content = $(".myClass").html();
我希望这会有所帮助!如果它有助于解决您的问题,请随时通过单击此答案左侧的 ✓ 将答案标记为已接受
var show_char = 280;
var ellipses = "... ";
var content = $(".myClass >*").html();
if (content.length > show_char) {
var a = content.substr(0, show_char);
var b = content.substr(show_char - content.length);
var html = a + "<span class=\'abc\'>" + ellipses + "</span><span class=\'abc\' style=\'display:none\'>" + b + "</span><a class=\'read-more\' href=\'#\'>Read more</a>";
$(".myClass").html(html);
}
$(".read-more").click(function(e) {
e.preventDefault();
$(".read-more").text() == "Read more" ? $(".read-more").text(" Read less") : $(".read-more").text("Read more");
$(".myClass .abc").toggle();
});
html {
font-size: 18px;
font-family: sans-serif
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="myClass">
<p><a href="https://stackoverflow.com/">stackoverflow</a> is a question and answer site for professional and enthusiast programmers. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange.</p>
</div>
推荐阅读
- javascript - 根据最近的日期对MongoDB中的集合进行排序
- prestashop - Prestashop 1.7 自定义模块前端控制器不起作用
- angular - 如何访问 PrimeNG 自动完成的“字段”属性内的数组元素
- java - 麻烦让我做......而循环工作 - Java
- typescript - 未捕获打字稿函数返回类型
- asp.net - EFCore 两个关系表如何相互导航?
- ms-access - 访问表 - 将现有字段更改为查找
- angular - 如何从通过 http.get 带来的数组中获取元素?
- excel - 在 UDF 的其他实例中输入数据时,UDF 会重新计算
- java - 在数据库 java NetBeans 中创建表权限被拒绝