如何使用 jQuery 动态启用/禁用链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3788946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:06:41  来源:igfitidea点击:

How do I dynamically enable/disable links with jQuery?

jqueryhyperlink

提问by GSto

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?

我在页面上显示了一些链接。我想根据页面上的其他事件启用/禁用它们。有没有办法用 jQuery 做到这一点?

回答by dekomote

$('selector_for_links_to_disable').bind('click', function(e){
        e.preventDefault();
})

and for enabling:

并启用:

$('selector_for_links_to_enable').unbind('click')

回答by pho3nixf1re

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.

一定要表明他们不再以某种方式工作,否则你的用户会感到困惑,哈哈。

回答by dave thieben

it depends on what you mean by "disable".

这取决于您所说的“禁用”是什么意思。

this will make them do nothing:

这将使他们什么都不做:

$("A").click(function() { return false; });

回答by Naveed

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

回答by Tibastral

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

委托比处理程序更好,因为您可以在加载 dom 之前调用它们

回答by Humberto Matias

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

当我通过 jquery 为按钮提供功能时,我喜欢这样做:

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

这样,您在第一次按下 de 按钮时即可获得该功能。现在您只需要为您的链接设置不同的 value1 索引即可再次工作