简体   繁体   English

如何使用 jQuery(或 js)禁用非输入元素?

[英]How to disable non-input elements with jQuery (or js)?

I am trying to disable a bunch of elements (divs that have onClick and other custom events) while a request is taking place.我正在尝试在请求发生时禁用一堆元素(具有 onClick 和其他自定义事件的 div)。

I have tried with:我尝试过:

$("selector").children().prop("disabled", true);

Also with:还有:

$("selector").children().attr("disabled", true);

Also with:还有:

$("selector").children().attr("disabled", "disabled");

Neither of these worked, meaning that, they all kept their functionality even after disabled was applied to them.这些都不起作用,这意味着即使在对它们应用禁用后,它们都保留了它们的功能。

To confirm that I am actually able to target all of the desired elements I tested with:为了确认我实际上能够针对我测试过的所有所需元素:

$("selector").children().css({backgroundColor: "black"});

All elements became black, so the targeting is correct.所有元素都变为黑色,因此定位正确。

I am open to any other suggestions on how to disable elements, basicly these are divs that should not be clickable (there are other events of interest, not just the click ), for the duration of a request, once a div is clicked, that is why I am trying to temporarily disable them, and re-enable them again, once I receive the response.我对如何禁用元素的任何其他建议持开放态度,基本上这些是不应单击的 div(还有其他感兴趣的事件,而不仅仅是click ),在请求期间,一旦单击 div,即这就是为什么我试图暂时禁用它们,并在收到响应后再次启用它们。

The disabled property only applies to input elements, such as <input> and <button> for example. disabled属性仅适用于输入元素,例如<input><button> It does not apply to some <div> or <li> styled to look like a button or input (could be a div content editable).它不适用于某些样式看起来像按钮或输入的<div><li> (可能是可编辑的 div 内容)。

To disable an element that is not a "real" input element, you can use $("selector").children().css({pointerEvents: "none"});要禁用不是“真实”输入元素的元素,可以使用$("selector").children().css({pointerEvents: "none"}); which will just prevent ALL events on that element and childs, no matter the event handlers binded.这只会阻止该元素和子元素上的所有事件,无论绑定了事件处理程序。

To restore: $("selector").children().css({pointerEvents: "initial"});恢复: $("selector").children().css({pointerEvents: "initial"});

pointer-events documentation指针事件文档




Edit to adress comments about keyboard events:编辑以解决有关键盘事件的评论:

$("selector").children().prop("tabIndex",-1); will avoid a tab navigation to access an <input> or <button> .将避免使用标签导航来访问<input><button>

tabindex documentation tabindex 文档

But since your elements are <div> ... I don't really think that is relevant.但是由于您的元素是<div> ...我真的不认为这是相关的。 But try it and see if that add-on code really is necessary and feel free to comment for future readers.但是尝试一下,看看这个附加代码是否真的有必要,并随时为未来的读者发表评论。 ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM