简体   繁体   中英

How to enable/disable Anchor Tag

Below example is working for enable/disable of href but not for onclick . I need to enable/disable for both attributes

Note: I cant simply remove/bind the onclick event to dummy function() as it need once we enable it.

Script Code:

<script type="text/javascript">
 $(document).ready(function () {
     $("#b1").click(function () {
         $("#yahoo").attr("disabled", "disabled");
         $("#yahoo").css("background-color", "silver");
     })

     $("#b2").click(function () {
         $("#yahoo").removeAttr("disabled");
         $("#yahoo").css("background-color", "white");
     })

     $("#yahoo").click(function (e) {
         if ($("#yahoo").attr("disabled") == "disabled") {
             e.preventDefault();
         }
     });
 });
</script>

HTML Code:

 <div>
   <input type="button" id="b1" value="Disable Yahoo Link"> 
   <input type="button" id="b2" value="Enable Yahoo Link">    
 </div>    
 <a id="yahoo" target="_blank" href="javascript:alert('href alert')" onclick="javascript:alert('onclick alert')">Yahoo.com</a>

Working Example http://jsfiddle.net/nunnakirankumar/suYe4/

Inside your click() function, you need to explicitly return false (after discovering it's disabled). Otherwise the default handler will cause the browser to go to or run the designated href.

The OP has most likely moved on, so this answer is really just for google searchers' sake.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM