jquery文本显示提示文本更改

时间:2014-02-27 03:52:56

标签: jquery html css

我正在创建一个FAQ页面,其中列出了问题但隐藏了解释 - 单击问题以显示解释。很直接的东西。

我想在隐藏解释时在“更多”的问题旁边添加一个小文字提示(在<span>中),在显示说明时添加“less”。无法弄清楚如何做到这一点。

尝试使用一些If / else语句,但无法让它们正常工作。有更简单的方法吗?

这是我当前的脚本,没有“更多/更少”文本更改:

$(document).ready(function() {
  $('.faqtitle').click(function () {
    $(this).next('p').animate({
            height: "toggle",
            opacity: "toggle"
        }, 400);
  });
});

...这里的小提琴通常显示我正在使用的内容: http://jsfiddle.net/V5LDQ/

谢谢!

4 个答案:

答案 0 :(得分:2)

这个怎么样:

$(document).ready(function() {
  $('.faqtitle').click(function () {
    $(this).next('p').animate({
            height: "toggle",
            opacity: "toggle"
        }, 400);
      var expand = $(this).find('span');
      if (expand.html() == "more") {
          expand.html("less");
      } else {
          expand.html("more");
      }
  });
});

工作小提琴here


编辑:

这是一个很好的简单方法,可以为文本更改添加一些css淡入淡出。这是使用jQuery fadeInfadeOut方法。可以找到其他文档here

  var expand = $(this).find('span');
  expand.fadeOut(500, function() {
      if (expand.html() == "more") {
          expand.html("less");
      } else {
          expand.html("more");
      }
      expand.fadeIn(500);
  });

与过渡here合作。

答案 1 :(得分:1)

<强> LIVE DEMO

  $('.faqtitle').click(function(){
    var io = this.io^=1;    // Toggler stored directly into the this object
    $(this)
       .next('p').animate({height: "toggle",opacity: "toggle"}, 400)
       .end().find('span').text( io?"less":"more" );
  });

.end()方法会将选择器返回给您单击的元素,而不是找到子节点'span'并使用条件运算符(?:)将根据布尔值设置文本我们使用^=1上的^var io AKA Bitwise XOR运算符)设置的值。单击按钮的布尔值直接存储在io(元素)对象(this)的属性this.io中。所以可以稍后检索。

所以解释.text( io?"less":"more" );
io分别存储1/0,知道条件中的1(这里我们使用?:)将在布尔true中评估我们说:

condition ? "use this if true" : "use that if false"

答案 2 :(得分:0)

您可以使用.toggle()

轻松完成此操作
$('.faqtitle').click(function () {
  $(this).next('p').toggle();
});

这是一个JSFiddle演示。

答案 3 :(得分:0)

试试这个。三元运营商很有趣。

      $('.faqtitle span').text() == 'more' ? $('.faqtitle span').text('less') : $('.faqtitle span').text('more');