Javascript 使用 JS / jQuery 启用/禁用 DOM 元素的事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8249641/
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
Enable/Disable events of DOM elements with JS / jQuery
提问by pabera
I stuck here with a little problem I have put pretty much time in which is pretty bad compared to its functionality.
我在这里遇到了一个小问题,我花了很多时间,与它的功能相比,这个问题非常糟糕。
I have tags in my DOM, and I have been binding several events to them with jQuery..
我的 DOM 中有标签,并且我已经使用 jQuery 将几个事件绑定到它们。
var a = $('<a>').click(data, function() { ... })
Sometimes I would like to disable some of these elements, which means I add a CSS-Class 'disabled' to it and I'd like to remove all events, so no events are triggered at all anymore. I have created a class here called "Button" to solve that
有时我想禁用其中的一些元素,这意味着我向它添加了一个“禁用”的 CSS 类,并且我想删除所有事件,因此不再触发任何事件。我在这里创建了一个名为“Button”的类来解决这个问题
var button = new Button(a)
button.disable()
I can remove all events from a jQuery object with $.unbind. But I would also like to have the opposite feature
我可以使用 $.unbind 从 jQuery 对象中删除所有事件。但我也想有相反的功能
button.enable()
which binds all events with all handlers back to the element OR maybe there is a feature in jQuery that actually nows how to do that?!
它将所有事件与所有处理程序绑定回元素,或者也许 jQuery 中有一个功能实际上现在如何做到这一点?!
My Button Class looks something similar to this:
我的按钮类看起来与此类似:
Button = function(obj) {
this.element = obj
this.events = null
this.enable = function() {
this.element.removeClass('disabled')
obj.data('events', this.events)
return this
}
this.disable = function() {
this.element.addClass('disabled')
this.events = obj.data('events')
return this
}
}
Any ideas? Especially this rebind functionality must be available after disable -> enable
有任何想法吗?特别是这个重新绑定功能必须在禁用 -> 启用后可用
var a = $('<a>').click(data, function() { ... })
I found these sources that did not work for me: http://jquery-howto.blogspot.com/2008/12/how-to-disableenable-element-with.html
我发现这些来源对我不起作用:http: //jquery-howto.blogspot.com/2008/12/how-to-disableenable-element-with.html
http://forum.jquery.com/topic/jquery-temporarily-disabling-events-> I am not setting the events within the button class
http://forum.jquery.com/topic/jquery-temporously-disabling-events-> 我没有在按钮类中设置事件
Appreciate your help.
感谢你的帮助。
回答by Jay
$("a").click(function(event) {
event.preventDefault();
event.stopPropagation();
return false;
});
Returning false is very important.
返回 false 非常重要。
Or you could write your own enable and disable functions that do something like:
或者您可以编写自己的启用和禁用功能,执行以下操作:
function enable(element, event, eventHandler) {
if(element.data()[event].eventHandler && !eventHandler) { //this is pseudo code to check for null and undefined, you should also perform type checking
element.bind(event, element.data()[event]);
}
else (!element.data()[event] && eventHandler) {
element.bind(event, element.data()[event]);
element.data({event: eventHandler}); //We save the event handler for future enable() calls
}
}
function disable(element, event) {
element.unbind().die();
}
This isn't perfect code, but I'm sure you get the basic idea. Restore the old event handler from the element DOM data when calling enable. The downside is that you will have to use enable() to add any event listener that may need to be disable() d. Otherwise the event handler won't get saved in the DOM data and can't be restored with enable() again. Currently, there's no foolproof way to get a list of all event listeners on an element; this would make the job much easier.
这不是完美的代码,但我相信你明白了基本的想法。调用 enable 时从元素 DOM 数据恢复旧的事件处理程序。缺点是您必须使用 enable() 添加可能需要 disable() d 的任何事件侦听器。否则事件处理程序将不会保存在 DOM 数据中,并且无法再次使用 enable() 恢复。目前,没有万无一失的方法来获取元素上所有事件侦听器的列表;这将使工作更容易。
回答by tere?ko
Instead of adding event handler to each element separately, you should use event delegation. It would make much more manageable structure.
您应该使用事件委托,而不是分别向每个元素添加事件处理程序。这将使结构更易于管理。
- http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/
- http://cherny.com/webdev/70/javascript-event-delegation-and-event-hanlders
- http://brandonaaron.net/blog/2010/03/4/event-delegation-with-jquery
- http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/
- http://cherny.com/webdev/70/javascript-event-delegation-and-event-hanlders
- http://brandonaaron.net/blog/2010/03/4/event-delegation-with-jquery
This why you can just check for class(es) on clicked element , and act accordingly. And you will be able even to re-eanble them , jsut by changing the classes of a tag.
这就是为什么您可以在单击的元素上检查类,然后采取相应的行动。您甚至可以通过更改标签的类来重新启用它们。
P.S. read the links carefully, so that you can explain it to others later. Event delegation is a very important technique.
PS仔细阅读链接,以便您以后可以向其他人解释。事件委托是一项非常重要的技术。
回答by Wojciech Bańcer
I would go on this with different approach:
我会用不同的方法继续这个:
<a id="link1">Test function</a>
<a id="link2">Disable/enable function</a>
<script type="text/javascript">
$(function() {
// this needs to be placed before function you want to control with disabled flag
$("#link1").click(function(event) {
console.log("Fired event 1");
if ($(this).hasClass('disabled')) {
event.stopImmediatePropagation();
}
});
$("#link1").click(function() {
console.log("Fired event 2");
});
$("#link2").click(function() {
$("#link1").toggleClass("disabled");
});
});
</script>
This may not be what you require, since it may effect also other functions binded into this event later. The alternative may be to modify the functions itself to be more like:
这可能不是您所需要的,因为它可能还会影响稍后绑定到此事件的其他函数。另一种方法可能是将函数本身修改为更像:
$("#link1").click(function(event) {
console.log("Fired event 1");
if ($(this).hasClass('disabled')) {
return;
}
// do something here
});
if that is an option.
如果这是一个选择。
回答by Zut
You could use an <input type="button">
and then use $("#buttonID").addAttr('disabled', 'disabled');
and $("#buttonID").removeAttr('disabled');
. Disabling and enabling will be handled by the browser. You can still restyle it to look like an anchor, if you need that, by removing backgrounds and borders for the button. Be aware though, that some margins and padding might still bugger u in some browsers.
您可以使用 an<input type="button">
然后使用$("#buttonID").addAttr('disabled', 'disabled');
and $("#buttonID").removeAttr('disabled');
。禁用和启用将由浏览器处理。如果需要,您仍然可以通过删除按钮的背景和边框来重新设置它的样式,使其看起来像一个锚点。但请注意,在某些浏览器中,某些边距和填充可能仍会困扰您。