我试图在用户点击链接时切换链接文本和内容。
我有类似的东西
<a id='link' href='#'>click me</a>
<div id='items'>
<h1>title here</h1>
<p>texts here...</p>
</div>
$('#link').on('click', function(e){
e.preventDefault();
$(this).text('isClicked');
$('#items').empty().html("<img src='images/image.png'/>")
})
当用户单击链接时,链接文本将变为 isClicked
并且 items
html 将被替换为图像。但是,如果用户再次点击,我希望看到链接文本变回 click me
并且 items
将隐藏图像并显示 title
和 p
再次标记内容。
我不确定如何完成此操作。谁能帮我解决这个问题?非常感谢!
最佳答案
您可以向链接添加一个虚拟类并使用该条件
//Have a dummy class added to the link and toggle it on click
$('#link').on('click', function(e){
e.preventDefault();
var $this = $(this),
$textDiv = $('#items'),
$imageDiv = $('#image')
if($this.hasClass('clicked')) {
// remove the class
$this.removeClass('clicked');
// change the text
$this.text('click me');
// Hide image
$imageDiv.addClass('hide');
// show text
$textDiv.removeClass('hide');
} else {
// remove the class
$this.addClass('clicked');
// change the text
$this.text('isClicked');
// Show image
$imageDiv.removeClass('hide');
// Hide text
$textDiv.addClass('hide');
}
});
您还可以链接应用于同一元素的方法。
关于javascript - 如何在我的案例中切换链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20359360/