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
2 Answers
Reset to default 6Probably 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
版权声明:本文标题:jquery - JavaScript mouseup Event Being Fired Multiple Times On Single Click - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742370454a2462134.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论