How to enable/disable Anchor Tag

梦想的初衷 提交于 2019-12-11 19:18:41

问题


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/


回答1:


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.



来源:https://stackoverflow.com/questions/16657351/how-to-enable-disable-anchor-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!