开发者

Prevent onclick action with jQuery

there are some links with onclick event actions

<a href="#" onclick="alert('panic!')">Let's panic</a>
<a href="#" onclick="alert('panic!')" disabled="disabled">I can't panic no more</a>

I need prevent event actons execution on links with disabled attribute without removing onclick actions.

$('a[disabled]').click(function(e){
  e.stopPropagation();
  return false;
});

This code doesn't helps me.

update Even this code doesn't work

<html><head><script type='text/javascript' src='jquery-1.3.2.js'></script></head>
<body>
<a href='#' onclick="alert('HA-ha!')" disabled="disabled" class="disabled">TEST</a>
<script type="text/javascript">
    $('a[disabled], a.disabled').click(function(e){
        console.log('override?');
        e.stopImmediatePropagation();           
            e.preventDefault();
        e.stopPropagation();
        return false;       
    });
</script>
</body></html开发者_JS百科>


jQuery is not going to solve this one OOTB. It can help, but none of stopPropagation, stopImmediatePropagation, preventDefault, return false will work if you simply attach them to the element. You need to override the element's click handler.

However you state in your question "without removing onclick actions". So you need to override the default behavior at the point the event is triggered, (as opposed to the cleaner approach of simply nulling out the onclick attribute for disabled anchors):

Here's what I mean:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Disable clicks</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
</head>
<body>
  <a href="#" onclick="alert('panic!')">Let's panic</a>
  <a href="#" onclick="alert('panic!')" disabled="disabled">I can't panic no more</a>

  <script>
  $('a[onclick]').each(function(){
    $(this).data('onclick', this.onclick);

    this.onclick = function(event) {
      if($(this).attr('disabled')) { // HERE
        return false;
      };

      $(this).data('onclick').call(this, event || window.event);
    };
  });
  </script>
</body>
</html>

Demo here.

The approach there is to override the inline click handler (onclick) with preemptive logic to catch the case where the anchor is "disabled" and then cancel the event (with return false).

The benefit there is that to enable an anchor again you simply .removeAttr('disabled') on it.


disabled isn't a property of anchors. Use something like rel='disabled' instead.

$('a[rel="disabled"]').click( function() { return false; } );

Update:

Ah, of course. It still fires the alert because it's actually inline in the markup! I never do that and so didn't notice. Take that click handler out of the markup and do it in jQuery in the first place and so you can then just do something like:

$('a').click( function() {
  if( $(this).attr('rel') == 'disabled' ) { return; }
  // do stuff here when not disabled
  return false; // so your '#' href doesn't get used
} );


The problem is that jQuery adds events in order. To stop other events, the events you need to stop must come after your stopping code. Since you have code in your on click, you will need to change up the order. This is what I would do:

<a href='#' onclick="alert('HA-ha!')" class="disabled">TEST</a>
<a href='#' onclick="alert('HA-ha!')">TEST</a>
<script type="text/javascript">
    $('a').each(function(){
        // Cache event
        var existing_event = this.onclick;

        // Remove the event from the link
        this.onclick = null;

        // Add a check in for the class disabled
        $(this).click(function(e){ 
            if($(this).hasClass('disabled')){
                e.stopImmediatePropagation();
                e.preventDefault();
            }                
        });

        // Reattach your original onclick, but now in the correct order
        // if it was set in the first place
        if(existing_event) $(this).click(existing_event);
    });
</script>

The benefit is just remove/add the disabled class using jQuery: $('a#whatever').addClass('disabled') or remove it $('a#whatever').removeClass('disabled') and no other cleanup/setup is required.


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:

<div>
    <a href="#" onclick="alert('panic!')">Let's panic</a>
    <a href="#" onclick="alert('panic!')" class="disabled">I can't panic no more</a>
</div>
<div>
    <input type="button" id="restoreClick" value="Restore" />
</div>


I found a pretty simple solution to preventing onclicks today, but keeping the action if you need it.

<a href="javascript:alert('panic!')" >Let's panic</a>
<a href="javascript:alert('panic!')" disabled="disabled">I can't panic no more</a>

$('a').click(function(e){
    if($(this).attr('disabled')) e.preventDefault();
});

I'm not a huge fan of using "javascript:", but this was by far the simplest solution to the problem.

Hope it helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜