jQuery 如何使用 javascript 在 <div> 上禁用然后启用 onclick 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18982642/
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 22:55:04  来源:igfitidea点击:

How to disable and then enable onclick event on <div> with javascript

javascriptjquery

提问by user2798259

Following is the code which i am trying

以下是我正在尝试的代码

document.getElementById("id").disabled = true;

回答by Tibos

You can use the CSS property pointer-eventsto disable the click event on any element:

您可以使用 CSS 属性pointer-events禁用任何元素上的单击事件:

https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events

// To disable:    
document.getElementById('id').style.pointerEvents = 'none';
// To re-enable:
document.getElementById('id').style.pointerEvents = 'auto'; 
// Use '' if you want to allow CSS rules to set the value

Here is a JsBin: http://jsbin.com/oyAhuRI/1/edit

这是一个 JsBin:http://jsbin.com/oyAhuRI/1/edit

回答by Paraphiliac Ostrich

I'm confused by your question, seems to me that the question title and body are asking different things. If you want to disable/enable a click event on a div simply do:

我对你的问题感到困惑,在我看来,问题标题和正文在问不同的事情。如果您想禁用/启用 div 上的点击事件,只需执行以下操作:

$("#id").on('click', function(){ //enables click event
    //do your thing here
});

$("#id").off('click'); //disables click event

If you want to disable a div, use the following code:

如果要禁用 div,请使用以下代码:

$("#id").attr('disabled','disabled');

Hope this helps.

希望这可以帮助。

edit: oops, didn't see the other bind/unbind answer. Sorry. Those methods are also correct, though they've been deprecated in jQuery 1.7, and replaced by on()/off()

编辑:哎呀,没有看到其他绑定/解绑答案。对不起。这些方法也是正确的,尽管它们在 jQuery 1.7 中已被弃用,并被 on()/off() 取代

回答by Somnath Kharat

To enable use bind()method

启用使用bind()方法

$("#id").bind("click",eventhandler);

call this handler

调用这个处理程序

 function  eventhandler(){
      alert("Bind click")
    }

To disable click useunbind()

禁用点击使用unbind()

$("#id").unbind("click");

回答by Renato Vianna

You can disable the event by applying following code:

您可以通过应用以下代码禁用该事件:

with .attr()API

.attr()API

$('#your_id').attr("disabled", "disabled");

or with .prop()API

或使用.prop()API

$('#your_id').prop('disabled', true);

回答by MichaC

First of all this is JavaScript and not C#

首先这是 JavaScript 而不是 C#

Then you cannot disable a div because it normally has no functionality. To disable a click event, you simply have to remove the event from the dom object. (bind and unbind)...

然后你不能禁用一个 div,因为它通常没有功能。要禁用单击事件,您只需从 dom 对象中删除该事件。(绑定和解绑)...