簡體   English   中英

使用jQuery防止onclick操作

[英]Prevent onclick action with jQuery

onclick事件操作有一些鏈接

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

我需要在具有禁用屬性的鏈接上執行阻止事件actons執行而不刪除onclick操作。

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

這段代碼對我沒有幫助。

更新即使這段代碼也行不通

<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不會解決這個OOTB。 它可以提供幫助,但是如果只是將它們附加到元素上, stopPropagationstopImmediatePropagationpreventDefaultreturn false都不起作用。 您需要覆蓋元素的單擊處理程序。

但是,您在問題中說“不刪除onclick操作” 所以,你需要重寫該點的事件被觸發,(而不是簡單地清潔方法的默認行為null荷蘭國際集團出onclick為殘疾人錨屬性):

這就是我的意思:

<!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>

在這里演示。

接下來的方法是使用搶先邏輯覆蓋內聯單擊處理程序( onclick )以捕獲錨被“禁用”的情況, 然后取消該事件( return false )。

這樣做的好處是,只需再次啟用錨點.removeAttr('disabled')就可以了。

disabled不是錨的財產。 請使用類似rel='disabled'

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

更新

啊,當然。 它仍會觸發alert因為它實際上是標記中的內聯! 我從來沒有這樣做過,所以沒有注意到。 將該單擊處理程序從標記中取出並首先在jQuery中執行,這樣您就可以執行以下操作:

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

問題是jQuery按順序添加事件。 要停止其他事件,您需要停止的事件必須停止代碼之后。 由於您在點擊時有代碼,因此您需要更改訂單。 這就是我要做的:

<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>

好處是使用jQuery刪除/添加禁用的類: $('a#whatever').addClass('disabled')或刪除它$('a#whatever').removeClass('disabled')並且沒有其他清理/ setup是必需的。

jQuery添加的任何點擊處理程序似乎在標記中添加的那些之后觸發。 我的解決方案是使用jQuery而不是標記來應用單擊處理程序,但是您可能沒有足夠的控制代碼來執行此操作。 如果你這樣做,那么根本不應用click處理程序來錨定禁用類的標簽(是的,我會使用類而不是不合適的屬性)。 如果您無法控制標記,那么您可能希望使用jQuery替換單擊處理程序,將其存儲以供以后重新應用。

   $(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;
              }
          });
      });
   });

經測試:

<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>

我找到了一個非常簡單的解決方案來防止今天的onclicks,但是如果你需要它可以保持動作。

<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();
});

我不是使用“javascript:”的忠實粉絲,但這是迄今為止最簡單的問題解決方案。

希望能幫助到你!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM