我有以下代码,它应该将h2的值从“Show More”更改为“Show Less”,然后在单击父级时再返回. if()测试正常并将文本更改为Show Less但它永远不会再将其更改回来并始终显示警告“Show More”,因
if()测试正常并将文本更改为Show Less但它永远不会再将其更改回来并始终显示警告“Show More”,因此它只是没有检测到else()条件.
我搜索了高低,找出原因但尚未找到解决方案.
我知道这是一个noob问题,所以为此道歉,但我在发布之前尝试找到解决方案.
谢谢.
$('#panels > .feature').click(function() { if($(this).children('h2').val('Show More')) { $(this).children('h2').text('Show Less'); alert('Show More was found'); } else { $(this).children('h2').text('Show More'); alert('Show Less was found'); } $(this).next(".info_box").animate( {'height':'toggle'}, 'slow', 'linear' ); });
有问题的HTML是:
<div id="panels"> <div id="Email" class="feature"> <h1>LiveContent</h1><h2>Show More</h2> </div> <div class="info_box">Information will go in this div which should slide in and out.</div> <div id="Email" class="feature"> <h1>Publishing Solutions</h1><h2>Show More</h2> </div> <div class="info_box">Information will go in this div which should slide in and out.</div> <div id="Email" class="feature"> <h1>Title 1</h1><h2>Show More</h2> </div> <div class="info_box">Information will go in this div which should slide in and out.</div> </div>您正在使用
.val()
来检查文本,而是使用
.text()
(并比较结果,不要设置它),如下所示:
if($(this).children('h2').text() == 'Show More')) { //here $(this).children('h2').text('Show Less'); alert('Show More was found'); } else { $(this).children('h2').text('Show More'); alert('Show Less was found'); }
此外,您可以使用.text()
和.slideToggle()
的功能将其整体减小,如下所示:
$('#panels > .feature').click(function() { $(this).children('h2').text(function(i, t) { return t == 'Show More' ? 'Show Less' : 'Show More'; }); $(this).next(".info_box").slideToggle("slow"); });
You can test it out here.