如何使用jQuery通过单击按钮启用和禁用链接

时间:2019-03-27 16:53:27

标签: javascript jquery

<script type="text/javascript">    
    $(document).ready(function(){        
        `$('#button1').click(function(){             
             $("a").removeAttr('href');
         }       
       });
    });
</script>`

<a href="https://youtube.com">link</a>`
<input id="button1" type="button" class="add" value="Click to remove the link!" />

2 个答案:

答案 0 :(得分:4)

您可以使用pointer-events:none

添加课程

$(document).ready(function() {
  $('#button1').click(function() {
    $("a").toggleClass('disable');

  });
});
.disable {
  pointer-events: none;
  cursor: no-drop;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#"> Link</a>
<button id='button1'>Click</button>

答案 1 :(得分:1)

您可以使用JQuery的pointer-events:none;方法来切换.toggleClass()样式的应用程序。

$(document).ready(function(){ 
    $("#toggle").on("click", function(event){
       $("a").toggleClass("disable");
    });
});
/* When applied to an element, the element doesn't respond to mouse actions */
.disable { pointer-events:none; } 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://example.com">Example.com</a>
<input type="button" id="toggle" value="Enable/Disable Link">

但是,如果您要询问如何完全删除链接,则可以使用.remove()方法:

$(document).ready(function(){ 
    $("#btnRemove").on("click", function(){
      $("a").remove();
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="https://example.com">Example.com</a>
 <input id="btnRemove" type="button" value="Click to remove the link!">