admin管理员组

文章数量:1334287

Can someone tell me why the javascript code below causes renewSession() to be called 7 times after a single click?

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

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

Can someone tell me why the javascript code below causes renewSession() to be called 7 times after a single click?

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

function renewSession() {
    $.ajax({
        url: "/Account/RenewSession",
        type: "POST"
    });
}
Share Improve this question asked Nov 21, 2011 at 22:24 thiag0thiag0 2,2295 gold badges34 silver badges51 bronze badges 1
  • The * selector is not good from performance and maintenance point of view. – Wojciech Bednarski Commented Nov 21, 2011 at 22:33
Add a ment  | 

2 Answers 2

Reset to default 6

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. 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).

You could use:

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

To prevent the multiple calls.


Edited to address ment from 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. 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. Anyway to get around this?

You could just target the body element; 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:

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

The * selctor matches 7 elements...

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!).

If this is not your intended behaviour either use a more specific selector, or call the stopPropagation method.

本文标签: jqueryJavaScript mouseup Event Being Fired Multiple Times On Single ClickStack Overflow