jQuery 切换 HTML 单击

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15154122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:29:02  来源:igfitidea点击:

jQuery Toggle HTML On Click

javascriptjquery

提问by John Mersal

When i click on the button the HTML changes, But when i click again, the slide toggle fires up but the I want to put back the html as Show Me.

当我单击按钮时,HTML 会发生变化,但是当我再次单击时,幻灯片切换会启动,但我想将 html 放回“Show Me”。

<div id="show">Show Me</div>
<div id="visible">Hello, My name is John.</div>

$(document).ready(function(){
    $("#show").click(function(){
        $('#visible').slideToggle();
        $('#show').html('Hide me');
    });
})

http://jsfiddle.net/u2p48/13/

http://jsfiddle.net/u2p48/13/

Any idea how is that done?

知道这是怎么做的吗?

Thank you

谢谢

回答by Adil

You can use conditional operator ? :to switch between texts.

您可以使用条件运算符? :在文本之间切换。

Live Demo

现场演示

$(document).ready(function(){
    $("#show").click(function(){
        $('#visible').slideToggle();            
        $('#show').html($('#show').text() == 'Hide me' ? 'Show Me' : 'Hide me');
    });
})

回答by dxh

You need to pass 'Show me'or 'Hide me'to .html, depending on whether you're showing or hiding. One way would be to check the visibility of #visiblebefore sliding:

您需要传递'Show me''Hide me'.html,具体取决于您是显示还是隐藏。一种方法是检查#visible滑动前的可见性:

var on = $('#visible').is(':visible');

and consequently:

因此:

$('#show').html(on ? 'Show me' : 'Hide me');

Demo

演示

回答by Zoltan.Tamasi

Look at this solution too:

也看看这个解决方案:

$("#show").click(function(){
    if ($('#visible').hasClass('visible')) {
        $('#visible').slideDown().removeClass('visible');
        $('#show').html('Hide me');
    } else {
        $('#visible').slideUp().addClass('visible');
        $('#show').html('Show Me');
    }    
});

http://jsfiddle.net/xkyf2/1/

http://jsfiddle.net/xkyf2/1/

回答by ardev

use a data attribute in your html

在你的 html 中使用 data 属性

 $('button').on('click', function(){
  var that = $('button');
  if(that.text() == that.data("text-swap")){
   that.text(that.data("text-original"));
  } else {
   that.data("text-original", that.text());
  that.text(that.data("text-swap"));
  } 
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button data-text-swap="Replace Text" data-text-original="Original Text">Original Text</button>