我有一个else语句,它将显示或隐藏一个read按钮,这取决于div中的字符数。
实际的if语句似乎有效--移除“读更多”按钮,但“其他if”似乎不起作用。
我的代码在下面
$('.hotel-copy').each(function () {
if ($(".sidebar-box").length < 194) { // if count is less than 193
$(".read-more").hide();
}
else if ($(".sidebar-box").length > 194) { // if count is greater than 193
$(".read-more").show();
}
});HTML
<div class="hotel-copy">
<div class="sidebar-box">
@if (!string.IsNullOrWhiteSpace(hotel.Description))
{
<p>@hotel.Description</p>
<p class="read-more"><a href="javascript:void(0);" class="button">Read more</a></p>
}
</div>
</div>CSS
/* READ MORE */
.accommodation-container .sidebar-box {
height: 120px;
position: relative;
overflow: hidden;
}
.accommodation-container .sidebar-box .read-more {
position: absolute;
bottom: 0px;
left: 0;
width: 100%;
/* text-align: center; */
margin: 0;
padding: 20px 0 0px 0;
background-image: linear-gradient(to top, #f7f7f7, #f7f7f7);
}任何帮助都将不胜感激。
谢谢
发布于 2018-06-13 10:37:05
使用此代码,将工作:
演示:https://codepen.io/creativedev/pen/jKwVXL
$('.hotel-copy').each(function () {
console.log($.trim($(this).children(".sidebar-box").children("p").text()).length)
if ($.trim($(this).children(".sidebar-box").children("p").text()).length < 194) { // if count is less than 193
$(this).children(".sidebar-box").children(".read-more").hide();
}
else if ($.trim($(this).children(".sidebar-box").children("p").text()).length >= 194) { // if count is greater than 193
$(this).children(".sidebar-box").children(".read-more").show();
}
});发布于 2018-06-13 10:38:33
如果要检查元素中文本的字符数,请使用text().length。length对象的jQuery属性(正如您最初使用的那样)用于检索集合中包含的元素数量,与您使用的选择器相匹配。
还请注意,您可以通过向toggle()提供一个布尔值而不是单独的show()/hide()调用来缩短逻辑:
$('.hotel-copy').each(function () {
$('.read-mode').toggle($(".sidebar-box").text().length >= 194);
});最后,我将操作符修改为>=,因为当文本的长度正好是194个字符时,没有覆盖的情况。
https://stackoverflow.com/questions/50834978
复制相似问题