jquery - 禁用单击

sci*_*ket 44 javascript jquery

我只想禁用用户在某些条件下单击元素的功能.以下是我正在使用的一些代码:

     $('#navigation a').bind('click',function(e){

    var $this   = $(this);
    var prev    = current;

    current = $this.parent().index() + 1; // store the position in current

    if (current == 1){
    $("#navigation a:eq(1)").unbind("click"); // i want to disable the ability to click this element if current is 1
    }
    if (current >= 2){
    $("#navigation a:eq(1)").bind("click"); // this is wrong, but I want to rebind the click if current is greater than 1.  
    }
Run Code Online (Sandbox Code Playgroud)

}

zzz*_*Bov 89

如果您使用的是jQuery版本1.4.3+:

$('selector').click(false);
Run Code Online (Sandbox Code Playgroud)

如果不:

$('selector').click(function(){return false;});
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法切换禁用点击功能而不是重新定义? (21认同)

ehu*_*kai 24

假设您使用点击事件,只需取消绑定.

if (current = 1){ 
    $('li:eq(2)').unbind("click");
}
Run Code Online (Sandbox Code Playgroud)

编辑:您目前是否正在将点击事件绑定到您的列表?根据你上面的评论,我想知道这是不是你真的在做什么?你如何实现点击?它只是一个锚(<a>标签)?更明确的信息将帮助我们回答您的问题.

更新:

有人玩过:eq()运算符.http://jsfiddle.net/ehudokai/VRGfS/5/

正如我所料,它是一个基于0的索引运算符.因此,如果您想在选择中选择第二个元素,那么您的选择就在哪里

$("#navigation a")
Run Code Online (Sandbox Code Playgroud)

你只需添加:eq(1)(第二个索引)然后.unbind("click")所以:

if(current == 1){
    $("#navigation a:eq(1)").unbind("click");
}
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩.

希望这可以帮助!


Ben*_*Ben 10

原始Javascript也可以很快完成同样的事情:

document.getElementById("myElement").onclick = function() { return false; } 
Run Code Online (Sandbox Code Playgroud)

  • 我以为这是一个错字,所以我在jQuery选择器中添加了“#”;) (2认同)

Jok*_*iro 5

您可以使用unbind方法删除已附加的处理程序...

if (current = 1){ 
   $('li:eq(2)').unbind('click');
}
Run Code Online (Sandbox Code Playgroud)

你可以查看什么可以解开吗?解开手册