Reputation: 656
I have some jquery tabs where some are loaded via ajax. When first loaded they are fine, the events fire once as required but when I click to a different tab and then go back to the tab loaded by ajax, the jquery events are fired twice, subsequent loads of the tab, add another event fire.. It seems the jquery is getting loaded again and again but when I inspect on chrome I can only see it once so I don't know whats going on. Any help would be appreciated.. Here is an example..
outerTabs.jsp
<html>
<head>
<link rel="stylesheet" href="${pageContext.servletContext.contextPath}/resources/css/jquery-ui.css">
<script type="text/javascript" src="${pageContext.servletContext.contextPath}/resources/js/jquery.js"></script>
<script type="text/javascript" src="${pageContext.servletContext.contextPath}/resources/js/jquery-ui.js"></script>
<script>var contextPath = "${pageContext.request.contextPath}";</script>
<script type="text/javascript">
$( document ).ready(function() {
$("#outerTabs").tabs();
});
</script>
</head>
<body>
<div id="outerTabs">
<ul>
<li><a href="#outerTab1">outerTab1</a></li>
<li><a href="${pageContext.servletContext.contextPath}/getTab2?param=param1">outerTab2</a></li>
</ul>
</div>
<div id="outerTab1"></div>
</body>
</html>
tab2.jsp
<html>
<head>
<script type="text/javascript">
$( document ).ready(function() {
$("body").on("click", "#link1", function(e) {
alert("clicked");
});
});
</script>
</head>
<body>
<a id="return">return</a>
<div id="tab1">
<a id="link1">
link1
</a>
</div>
</body>
</html>
controller
@Controller
public class Controller {
@RequestMapping(value = { "/loadTabs" }, method = RequestMethod.GET)
public ModelAndView loadTabs() {
ModelAndView model = new ModelAndView();
model.setViewName("outerTabs");
return model;
}
@RequestMapping(value = { "/getTab2" }, method = RequestMethod.GET)
public ModelAndView getTab1(@RequestParam("param") String param) {
ModelAndView model = new ModelAndView();
model.addObject("tab2Content", null);
model.setViewName("tab2");
return model;
}
}
So in this example when I load tab 2 and then click back to tab1 and then click tab 2 again, clicking the link1 link causes alert to display twice.
Upvotes: 0
Views: 664
Reputation: 34
It is not JQuery being loaded, but the event being rebind over and over. One option would be having an 'is-bound' flag. Such as:
$("body").on("click", "#link1:not(.is-bound)", function(e) {
alert("clicked");
$(this).addClass('is-bound');
});
This way your function will trigger only if the element was not previously bound.
Upvotes: 1
Reputation: 893
You give the element #link1 the click-event again on every reload. You could use the http://api.jquery.com/off/ of the jquery-lib to avoid the second alert. Here is an example:
$( document ).ready(function() {
$("#link1").off("click").on("click", function(e) {
alert("clicked");
});
});
Upvotes: 2