How do I dynamically enable/disable links with jQuery?

后端 未结 6 739
执笔经年
执笔经年 2020-12-01 05:08

I have some links displayed on a page. I would like to enable/disable them based on other events on the page. Is there a way to do this with jQuery?

相关标签:
6条回答
  • 2020-12-01 05:44
    $('selector_for_links_to_disable').bind('click', function(e){
            e.preventDefault();
    })
    

    and for enabling:

    $('selector_for_links_to_enable').unbind('click')
    
    0 讨论(0)
  • 2020-12-01 05:49

    it depends on what you mean by "disable".

    this will make them do nothing:

    $("A").click(function() { return false; });
    
    0 讨论(0)
  • 2020-12-01 05:51

    When I am giving functions to the buttons by jquery, I like to do this:

    indice = '';
    
    $('myLink').live('click',function() {
        if (indice !== 'value1'){
    
            // your code
        }
    
        indice = 'value1';
        return indice;
    
    });
    

    with this, you get the function just the first time you press de button. Now you just have to set indice different of value1 to your link works again

    0 讨论(0)
  • 2020-12-01 05:53

    You can do something like this:

    <script>
        $(document).ready(function() {
            $('input#disableall').live('click', function(){
                $('a').attr( 'class', 'disabled' );
                alert('All links are disabled.');
            });
    
    
            $('input#enableall').live('click', function(){
                $('a').attr( 'class', 'enabled' );
                alert('All links are enabled.');
            });
    
            $('a.disabled').live('click', function(event){
                event.preventDefault();
            });
        });
    </script>
    
    <a href='http://www.google.com'>Google<a/>
    <a href='http://www.yahoo.com'>Yahoo<a/>
    <a href='http://www.hotmail.com'>Hotmail<a/>
    
    <input type='button' id='disableall' value='Disable Links' />
    <input type='button' id='enableall'  value='Enable Links' />
    
    0 讨论(0)
  • 2020-12-01 05:53
    $(document).delegate('.links', 'click', function () {
      if ([your condition is true]) {
        return false;
      }
    })
    

    delegation is better than handlers, because you can call them before the dom is loaded

    0 讨论(0)
  • 2020-12-01 05:56

    You could do something like:

    $('.links').click(function(e){
      if( [some conditions] ){
        e.preventDefault();
      }
    });
    

    Be sure to show that they no longer work somehow, otherwise your users will get confused, lol.

    0 讨论(0)
提交回复
热议问题