javascript - 如何在我的案例中切换链接?

标签 javascript jquery html css

我试图在用户点击链接时切换链接文本和内容。

我有类似的东西

<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 将隐藏图像并显示 titlep 再次标记内容。

我不确定如何完成此操作。谁能帮我解决这个问题?非常感谢!

最佳答案

您可以向链接添加一个虚拟类并使用该条件

//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'); 
     }
 });

Check Fiddle

您还可以链接应用于同一元素的方法。

关于javascript - 如何在我的案例中切换链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20359360/

相关文章:

html - 空间从何而来,如何去掉id?

javascript - 除 1 个部分外禁用滚动

jquery Draggable +sortable 与自定义 html 的放置事件?

javascript - jQuery width() 不起作用

javascript - 使用 jquery 提取 URL 片段

html - 这里面的原理是什么?

html - 与 div 元素不同,具有 contenteditable 的 Span 元素不会自然失去焦点

javascript - JQuery 使用类标签附加 HTML onclick

javascript - document.write() 是做什么的?

javascript - 将 Canvas 无重复图案填充居中