jQuery   发布时间:2022-04-19  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了jquery切换文本只更改一次大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下代码,它应该将h2的值从“Show More”更改为“Show Less”,然后在单击父级时再返回.

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.

大佬总结

以上是大佬教程为你收集整理的jquery切换文本只更改一次全部内容,希望文章能够帮你解决jquery切换文本只更改一次所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。