English 中文(简体)
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>
最佳回答

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!





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签