简体   繁体   English

jQuery .click() 正在点击,但它不应该

[英]jQuery .click() is clicking, but it shouldn´t

while testing my JavaScript I have the following problem:在测试我的 JavaScript 时,我遇到了以下问题:

$('#idOfMyElement').click();

is executed.被执行。 But I want to verfiy with my test, that is is not executed, because it has the following CSS:但我想验证我的测试,即没有执行,因为它具有以下 CSS:

<span style="cursor: not-allowed; pointer-events: none;" id="idOfMyElement"></span>

I debugged it and it is sure, that when the .click() is executed, it has DEFINITELY the mentioned CSS-attributes.我调试了它,可以肯定的是,当执行.click() ,它肯定具有提到的 CSS 属性。 In my normal program it works (means that the click doesn´t work), but in my test the click works, even if it shouldn´t.在我的正常程序中它有效(意味着点击不起作用),但在我的测试中点击有效,即使它不应该。

I have no clou, what might be the problem.我没有clou,可能是什么问题。 Thanks for your help!谢谢你的帮助!

Looks like in your test you are triggering the event programmatically by using $('#idOfMyElement').click();看起来在你的测试中你是通过使用$('#idOfMyElement').click();编程方式触发事件的$('#idOfMyElement').click(); ; ; in that case it is not bound by the CSS mouse rules, and thus the click handlers will get executed.在这种情况下,它不受 CSS 鼠标规则的约束,因此单击处理程序将被执行。

You need to check the mouse pointer rules before triggering the click event in your test suite.触发测试套件中的单击事件之前,您需要检查鼠标指针规则。

Pointer events only respond correctly to a real pointer event.指针事件只正确响应真正的指针事件。 If you trigger click() function it fires in all times that you make it.如果您触发 click() 函数,它会在您创建它的所有时间触发。 Just add a condition reading if pointer events is active or replace it by a disabled attribute如果指针事件处于活动状态,只需添加条件读数或将其替换为禁用属性

Prevent the default click event using jQuery:使用 jQuery 防止默认点击事件:

$('#idOfMyElement').on('click', function(e) {
  e.preventDefault(); });

* UPDATE * * 更新 *

Now that I know what you're trying to do, I highly recommend using javascript over CSS for this because CSS does not work the way you're trying to use it – Javascript does.既然我知道您要做什么,我强烈建议您为此使用 javascript 而不是 CSS,因为 CSS 无法按照您尝试使用的方式工作 - Javascript 可以。 Instead of using CSS attributes, use Javascript variables.不要使用 CSS 属性,而是使用 Javascript 变量。

When you want the element to be clickable,当您希望元素可点击时,

$('#idOfMyElement').prop('disabled', false);

When it should be unclickable,当它应该无法点击时,

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

The browser takes care of the cursor without needing CSS, and click events should react appropriately.浏览器在不需要 CSS 的情况下处理光标,并且点击事件应该做出适当的反应。 Hope that was helpful!希望这是有帮助的!

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

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