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
jQuery Toggle HTML On Click
提问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');
});
})
Any idea how is that done?
知道这是怎么做的吗?
Thank you
谢谢
回答by Adil
回答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 #visible
before sliding:
您需要传递'Show me'
或'Hide me'
到.html
,具体取决于您是显示还是隐藏。一种方法是检查#visible
滑动前的可见性:
var on = $('#visible').is(':visible');
and consequently:
因此:
$('#show').html(on ? 'Show me' : 'Hide me');
回答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');
}
});
回答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>