javascript - 重新加载后相同的功能不给出相同的结果
问题描述
所以基本上,我的页面是一个商店,所以内容是用 php 短代码生成的,如下所示:
<?php get_header(); ?>
<div id="main-content">
<div id="page-content">
<?php
echo do_shortcode('[products limit="20" columns="4" category="t-shirt"]');
?>
</div>
</div>
<?php get_footer(); ?>
<script>$(document).ready(linebreak)</script>
所以它给了我一个像这样的基本页面,我的内容是一个元素列表:
<html>
<head></head>
<body>
<div id="main-content">
<div id="page-content">
<ul class="my-list">
<li class="my-element">
<img>
<h2>A title</h2>
</li>
<li class="my-element">
<img>
<h2>A title</h2>
</li>
</ul>
</div>
</div>
<footer></footer>
</body>
</html>
<script>$(document).ready(linebreak)</script>
Acutally 有超过 20 里,但你可以看到我的页面是什么样子的。我正在使用 linebreak jquery 函数来检查我的 h2 标题是否有换行符,因为我不想要它。如果有换行符,它只是保留前 20 个字符并在末尾添加“...”。它工作得很好,除了一个或一个 h2 并不总是根据我的重新加载而改变。它们确实有换行符,但是当我多次重新加载页面时,有时该功能会更改它们,有时则不会。它只有一两个特定的 h2 并且总是相同的。为什么每次运行我的页面时我的函数都没有给出相同的结果?
如果它可以提供帮助,这是我的 script.js 中包含在标题中的函数:
function linebreak(){
$("#main-content #page-content .woocommerce ul li h2").each(function(index){
var lheight = Math.round(parseFloat($("#main-content #page-content ul li h2").css("line-height")));
var title = $(this).text().trim().substring(0, 100).split("").slice(0, 21).join("") + "...";
if ($(this).height() > lheight){
$(this).html(title);
}
});
};
解决方案
你有你想要的形象吗?用 CSS 来管理太长的标题不是更容易吗?
如果标题太长,如果您为 h2 元素设置宽度,以下代码将自动添加省略号。
例如
h2 {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
推荐阅读
- docker - 如何将 OpenSSL 版本从 OpenSSL 1.0.1t 更新到 OpenSSL 到 1.1.1u
- java - 为什么这个 parseInt 抛出数组越界异常?
- ruby - 如何通过 Ruby PostgreSQL gem 获取自动生成的行主键?
- django - Django - serve() 得到了一个意外的关键字参数“documuent_root”
- function - 如何在没有短代码 Woocommerce 的情况下将所有产品属性放在描述下方
- angularjs - Angular 6中NGPrime数据表中的多个复选框过滤
- javascript - 从 C++ 调用 Node JS javascript
- javascript - 如何循环播放嵌入的 Facebook 视频?
- objective-c - AVPlayerViewController 默认控件的自定义View
- unit-testing - Sinon.js 结合调用的次数