单击链接时切换文本
我有以下代码将div(称为#extra
)切换到视图中:
$('#more').click(function() { $('#extra').slideToggle('fast'); return false; });
我的点击function是这个链接:
More about us
当#extra
div可见时,如何将“关于我们的更多信息”文本更改为“少关于我们”? 当点击相同的链接隐藏div时,我希望链接的文本更改为“更多关于我们”。
只是切换文字?
$('#more').click(function() { $('#extra').slideToggle('fast'); $('#more').text(function(_,txt) { var ret=''; if ( txt == 'More about us' ) { ret = 'Less about us'; $(this).css('background','url(link/to/image1.png)'); }else{ ret = 'More about us'; $(this).css('background','url(link/to/image2.png)'); } return ret; }); return false; });
使用此代码:
$('#more').click(function() { jQuery(this).text('less about us'); if($('#extra').is(':visible')){ jQuery(this).text('Less about us'); }else{ jQuery(this).text('More about us'); } $('#extra').slideToggle('fast'); return false; });
这是演示: http : //jsfiddle.net/AAFaY/
试试这个
$('#more').click(function() { var more = $(this); $('#extra').slideToggle('fast', function(){ more.html(s.text() == 'More about us' ? 'Less about us' : 'More about us'); }); return false; });
演示
是的,因为这个Dinesh的解决方案可能是jQuery中最有效的优雅结果
$(document).ready(function() { $('#more').click(function() { var s = $(this); $('#extra').slideToggle('fast', function() { s.html(s.text() == 'More..' ? 'Less..' : 'More..'); }); return false; }); });
#wrapp { height: 38vh; width: 40vw; margin: 50px 50px; left: 10%; background-color: blue; position: absolute; } #wrapp #more { display: inline-block; padding: 5px; background: yellow; } #extra { height: 100px; width: 250px; position: relative; margin: 1.2vh auto; } #extra p { position: relative; color: red; text-align: center; vertical-align: center; padding-top: 3.6vh; font-size: 2.5em; font-weight: bold; }
Document
$(document).ready(function() { $('#more').click(function() { var s = $(this); $('#extra').slideToggle('fast', function() { s.html(s.text() == 'More..' ? 'Less..' : 'More..'); }); return false; }); });
#wrapp { height: 38vh; width: 40vw; margin: 50px 50px; left: 10%; background-color: blue; position: absolute; } #wrapp #more { display: inline-block; padding: 5px; background: yellow; } #extra { height: 100px; width: 250px; position: relative; margin: 1.2vh auto; } #extra p { position: relative; color: red; text-align: center; vertical-align: center; padding-top: 3.6vh; font-size: 2.5em; font-weight: bold; }
Document