jQuery .toggle()替代品? [英] jQuery .toggle() Alternative?

查看:136
本文介绍了jQuery .toggle()替代品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,jQuery删除了.toggle(),而且我不知道如何在按钮内切换文本.是的,我一直在这个论坛附近寻找答案,但是没有一个足够的答案.

Recently, jQuery removed .toggle(), and I don't know how to toggle text within a button. And yes, I've looked around this forum for an answer, but none were adequate.

这是我的代码:

$("#show").click(function () {
if($(this).text() == "Show") {
    $(this).text() == "Hide";
    alert("Fill fields");
} else {
    $(this).text() == "Show";
    alert("Clear fields");
}
});

说明:

  • 单击#show时,执行匿名功能.
  • 如果文本为显示",则更改为隐藏"
  • 然后,提醒填充字段"
  • 否则,将文本更改为显示"
  • 提示清除字段"

小提琴.

推荐答案

.text()的设置器是这样的:

$(selector).text('text here') // this is setter

不是

$(selector).text() == 'text here'; // this is comparison

完整的代码:

$("#show").click(function () {
    if($(this).text() == "Show") {
        $(this).text("Hide");
        alert("Fill fields");
    } else {
        $(this).text("Show");
        alert("Clear fields");
    }
});

演示

如果需要,可以使用三元运算符将其缩短:

You can shorten it with ternary operators if you want to:

$('#show').click(function(){
   $(this).text(function(_, text) { return text == 'Show' ? 'Hide' : 'Show'; });    
});

这篇关于jQuery .toggle()替代品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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