Javascript Jquery else if语句没有';我好像不工作
我有一个else-if语句,根据div中的字符数显示或隐藏一个read-more按钮 实际的if语句似乎起作用了——它删除了readmore按钮,但elseif似乎不起作用 我的代码在下面Javascript Jquery else if语句没有';我好像不工作,javascript,jquery,Javascript,Jquery,我有一个else-if语句,根据div中的字符数显示或隐藏一个read-more按钮 实际的if语句似乎起作用了——它删除了readmore按钮,但elseif似乎不起作用 我的代码在下面 $('.hotel-copy').each(function () { if ($(".sidebar-box").length < 194) { // if count is less than 193 $(".read-more").hide(); } el
$('.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();
}
});
任何帮助都将不胜感激
谢谢使用此代码,可以: 演示:
$('.hotel copy')。每个(功能(){
console.log($.trim($(this).children(“.sidebar框”).children(.p”).text()).length)
if($.trim($(this).children(“.sidebar框”).children(.p”).text()).length<194){//如果计数小于193
$(this.children(“.sidebar框”).children(“.read more”).hide();
}
else if($.trim($(this).children(“.sidebar框”).children(.p”).text()).length>=194){//如果计数大于193
$(this.children(“.sidebar框”).children(“.read more”).show();
}
});
如果要检查元素中文本的字符数,请使用text().length
。jQuery对象的length
属性(正如您最初使用的那样)用于检索集合中包含的与您使用的选择器匹配的元素数
还请注意,您可以通过向toggle()
提供布尔值来缩短逻辑,而不是单独的show()
/hide()
调用:
$('.hotel-copy').each(function () {
$('.read-mode').toggle($(".sidebar-box").text().length >= 194);
});
最后,我将操作符修改为
=
,因为当文本的长度正好是194个字符时,没有大小写覆盖。“$(“.sidebar box”)。length
不会给出字符的长度,而是返回包含sidebar box
类元素的jQuery对象的长度。try$(“.sidebar-box”).text().length
或$(“.sidebar-box”).val().length
请注意,您的条件与注释不匹配。当length==194
标记的答案使用jQuery.text()时,您没有理由.length
来确定长度。当仅使用选择器时,您将查询匹配元素的数量。那么当length==194时呢?@ADyson对OP提出更多问题,因为这可能是有意的,OP不想更改194上的任何内容。-尽管我相信这很可能是OP的疏忽。假设空格不被视为有效字符,特别是带有show more and less的字符,这是非常冒昧的。空格通常是句子中的有效字符,应该触发show more/less功能。如果文本开头有200个空格,后面跟着20个字符,您现在就看不到这20个字符了。@bhumi我试过了,但它没有显示出来oesn似乎不起作用。当我复制并粘贴到控制台并更改.hotel copy to.sidebar框时,它似乎隐藏了“阅读更多”按钮,但当粘贴到脚本文件中并进行调试时-没有任何效果:/-我已经包含了我的HTML和CSSalso@Danzel91:根据html更新代码。现在应该可以工作了。
/* 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);
}
$('.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();
}
});
$('.hotel-copy').each(function () {
$('.read-mode').toggle($(".sidebar-box").text().length >= 194);
});