使用jQuery切换文本 [英] Toggle Text with jQuery

查看:86
本文介绍了使用jQuery切换文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里找到了有关该主题的几篇文章,但似乎都没有确切地回答我在寻找什么.

I've found a a few articles here on this topic but none seem to answer exactly what I'm looking for.

这是我当前的代码:

    $(".email-slide").click(function(){
    $("#panel").slideToggle("slow");
    $(this)
    .text("Close")
    .toggleClass("active");
});

当我选择具有"email-slide"类的单词"Email"时,顶部面板会向下滑动,单词"Email"变成白色,单词"Email"变成单词"Close".

When I select the word "Email" which has the class "email-slide" the top panel slides down, and the word "Email" turns to white, and the word "Email" turns into the word "Close".

到目前为止一切都很好.但是,当单击关闭"时,尽管颜色和面板恢复正常,但单词关闭"不会变回单词电子邮件".我尝试使用.toggleText("class")而不是.text("Close"),但似乎不起作用.有没有类似的事情我可以通过添加尽可能少的代码来完成呢?谢谢!

All good so far. But when clicking "Close" though the color and panel go back to normal, the word "Close" does not turn back into the word "Email". Instead of .text("Close") I tried .toggleText("class") but it seems that does not work. Is there something similar I could do it accomplish it by adding the least amount of code possible? Thank you!

更新-我可以使用以下代码完成此操作,但希望这样做会更高效/更快捷.如果没有,请告诉我.谢谢!

UPDATE - I am able to accomplish it by using the following code, but was hoping that would be a more efficient/shorter way of doing it. If not, let me know. Thanks!

$(".email-slide").click(function(){
    $("#panel").slideToggle("slow");
    $(this).toggleClass("active");
});

$(".email-slide").toggle(function (){
    $(this).text("Close")
}, function(){
    $(this).text("Email")
});

推荐答案

您可以尝试:

$(".email-slide").click(function() {
    $("#panel").slideToggle("slow");

    $(this).toggleClass("active");

    if ($(this).text() == "Close")
       $(this).text("Email")
    else
       $(this).text("Close");

});

或者也可以不比较text()值,也可以测试$(this).hasClass("active").

Or instead of comparing the text() value, you can also test for $(this).hasClass("active").

H.t.h. :)

这篇关于使用jQuery切换文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆