Предотвратите onclick действие с jQuery

К сожалению, это не находится в самой Платформе.NET. Мое желание состоит в том, что Вы могли интегрироваться с FileZilla, но я не думаю, что он представляет интерфейс. У них действительно есть сценарии, я думаю, но это не будет столь же чисто, очевидно.

я использовал CuteFTP в проекте, который делает SFTP. Это представляет COM-компонент, который я создал обертку.NET вокруг. Выгода, Вы найдете, является полномочиями. Это работает красиво под учетными данными Windows, которые установили CuteFTP, но работающий под другими учетными данными требует, чтобы полномочия были установлены в DCOM.

30
задан Andrew Rumm 18 November 2009 в 14:50
поделиться

4 ответа

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.

55
ответ дан 27 November 2019 в 23:31
поделиться

Любые обработчики кликов, добавленные jQuery, похоже, срабатывают после тех, которые добавлены в разметку. Моим решением было бы применить обработчики кликов с помощью jQuery вместо разметки, но у вас может не хватить контроля над кодом для этого. Если вы это сделаете, просто не применяйте обработчик кликов к тегам привязки с отключенным классом (и, да, я бы использовал класс, а не несоответствующий атрибут). Если у вас нет контроля над разметкой, вы можете заменить обработчик кликов с помощью 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>
1
ответ дан 27 November 2019 в 23:31
поделиться

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.

5
ответ дан 27 November 2019 в 23:31
поделиться

отключено не является свойством якорей. Вместо этого используйте что-то вроде rel = 'disabled' .

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

Обновление :

Ах, конечно. Он по-прежнему запускает предупреждение , потому что он фактически встроен в разметку! Я никогда этого не делал и поэтому не замечал. Выньте этот обработчик кликов из разметки и сделайте это в первую очередь в 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
} );
8
ответ дан 27 November 2019 в 23:31
поделиться
Другие вопросы по тегам:

Похожие вопросы: