2010-11-29 42 views
3

我有下面的代码应该被点击父当从“显示更多”,以“显示更少”的h2的值更改,然后再回来。jQuery的切换文本只改变一次

的,如果()测试确定,改变了文本显示更少,但它绝不会再次改变它,总是显示警报“显示更多”,所以它只是没有检测到其他()条件。

我已搜查高和低,找出原因,但还没有找到一个解决办法。

我知道这是一个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> 
+0

对于格式良好的问题+1。 – Matt 2010-11-29 13:12:30

回答

2

您使用.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

3
if($(this).children('h2').val('Show More')) { 

如果有这样的的.text区段代替.VAL?

+0

是的,`.val()`用于获取输入元素的值,如`input`或`select`,`.text()`获取内部文本。 – Albireo 2010-11-29 13:12:12

+0

多数民众赞成多多少少我认为,只是不想看起来愚蠢:) – benhowdle89 2010-11-29 13:12:42

1

功能.val('Show More)尝试设置的HTML属性value为'Show More'。如果你把它叫做不带参数,它将作为一个吸气,而不是制定者 - 这是你想要的。但对于文字而言,并非价值。

所以不是.val('Show More'),你要像.text() == 'Show More'

1

您正在设置文本而不是比较它。使用text方法不带参数来获取值,然后比较一下:

if($(this).children('h2').text() == 'Show More') 

的代码不能正常工作,甚至是第一次,因为它总是做同样的事情。它似乎第一次工作的原因是,它总是在第一次做它应该做的事情。