Prevent onclick action with jQuery

前端 未结 5 828
春和景丽
春和景丽 2020-11-30 05:01

there are some links with onclick event actions

Let\'s panic


        
5条回答
  •  眼角桃花
    2020-11-30 05:08

    Any click handlers added by jQuery seem to fire after those added in the mark up. My solution would be to apply the click handlers using jQuery instead of in the mark up, but you may not have enough control over the code to do this. If you do, then simply don't apply the click handler to anchor tags with class disabled (and, yes, I would use a class rather than an inappropriate attribute). If you don't have control over the mark up, then you might want to replace the click handler using jQuery, storing it for later reapplication.

       $(function() {
          $('a.disabled').each( function() {
             var $this = $(this);
             var click = $this.attr('onclick');
             if (click) {
                 $this.data('click',click);
                 // add return false to prevent default action
                 $this[0].onclick =  function() { return false; };
             }
          });
    
          $('#restoreClick').click( function() {
              $('a.disabled').each( function() {
                  var $this = $(this);
                  $this.removeClass('disabled');
                  var click = $this.data('click');
                  if (click) {
                      $this[0].onclick = click;
                  }
              });
          });
       });
    

    Tested with:

    
    

提交回复
热议问题