简体   繁体   English

一次单击多次触发JavaScript mouseup事件

[英]JavaScript mouseup Event Being Fired Multiple Times On Single Click

Can someone tell me why the javascript code below causes renewSession() to be called 7 times after a single click? 有人可以告诉我,为什么下面的javascript代码一次单击后会导致renewSession()被调用7次吗?

$(document).ready(function () {
    $("*").mouseup(function () {
        renewSession();
    });
});

function renewSession() {
    $.ajax({
        url: "/Account/RenewSession",
        type: "POST"
    });
}

Probably it's because the mouseup event propagates up through the DOM tree, and you're applying the handler to every element in the document. 可能是因为mouseup事件在DOM树中向上传播,并且您将处理程序应用于文档中的每个元素。 So it'll fire on the first element, and then the parent and so on until it gets to the html (or the body , I can never quite remember without checking every time). 因此,它将首先在第一个元素上触发,然后在父元素上触发,依此类推,直到到达html (或body ,如果没有每次检查,我将永远不会记得)。

You could use: 您可以使用:

$(document).ready(function () {
    $("*").mouseup(function (e) {
        e.stopPropagation();
        renewSession();
    });
});

To prevent the multiple calls. 防止多次通话。


Edited to address comment from thiag0: 编辑以解决thiag0的评论:

Thanks for the quick response...what I am trying to do is call renewSession() every time the user clicks on the site to keep the session alive. 感谢您的快速响应...我想做的是每当用户单击该站点以保持会话活动时调用renewSession()。 This solution prevents the renewSession from getting called multiple times in a single click but prevents the actual intent of the user's click from firing. 此解决方案可防止一次单击即可多次调用renewSession,但可以防止触发用户点击的实际意图。 Anyway to get around this? 无论如何要解决这个问题?

You could just target the body element; 您可以只针对body元素; so long as events are allowed to propagate through the DOM tree (so long as you're not calling event.stopPropagation() on elements between the element clicked on (or 'mouseup'-ed) then the event(s) will propagate to the body . So I'd suggest using: 只要事件被允许通过DOM树传播(只要您不对单击(或“鼠标”编辑的)元素之间的元素调用event.stopPropagation() ,那么事件将传播到的body ,所以我建议使用:

 $(document).ready(function () { $("body").mouseup(function () { renewSession(); }); }); 

The * selctor matches 7 elements... *选择符匹配7个元素...

Events in html bubble up the DOM tree, unless explicitly told to stop, and hence the event will be triggered for each element going up the tree that matches the selector (in this case all of them!). html中的事件会在DOM树上冒出气泡,除非明确告知要停止,因此该事件将针对与选择器匹配的树中的每个元素(在本例中都是所有元素)触发。

If this is not your intended behaviour either use a more specific selector, or call the stopPropagation method. 如果这不是您的预期行为,请使用更具体的选择器,或调用stopPropagation方法。

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

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