So as many others I have a problem dealing with scripts from external pages I load with ajax.
Im trying to set up a page with an "admin panel" on top of it. I want to be able to navigate to several admin pages within the panel. The different admin pages have both internal <script>
and external js-files that they include. The scripts are loaded as they should but they seem to stack up or are not being managed in a good way.
I made a small test on one of the admin pages:
$('.left-col').click(function () {
alert();
});
Here, whenever I return to this page it will bind another click to it so I then get two alerts each time I click the div. I can solve this easily by running $('.left-col').unbind();
in my ajax.success.
However for some admin pages there are tons of .click/.change/.live etc and I'm not even sure what they are (i.e. from external plugins). So can I somehow unbind/remove all of the scripts loaded from each of my ajax-loaded page without having to specify each elements? I know I can use selectors with unbind but it doesnt seem very effective to loop over each 开发者_运维百科div/img/input etc and unbind, and I'm not even sure if it will work.
This is how I load the admin pages:
<script type="text/javascript">
$(document).ready(function() {
function reloadAdminPanel(url) {
if(typeof(url) === "undefined") {
var url = '/admin/panel/dashboard/';
}
$.ajax({
'success': function (data, textStatus) {
var jData = $(data);
// override links in admin to run reloadAdminPanel()
jData.find('a').each(function() {
var newUrl = $(this).attr('href');
$(this).click(function(e) {
reloadAdminPanel(newUrl);
return false;
});
});
$('div.panel__inner').remove();
$('body').prepend(jData);
delete jData;
},
'url': url
});
}
reloadAdminPanel();
});
</script>
Any help is appreciated, cheers!
The structure of the page:
<html>
<body>
<div class="panel__inner"> <!-- admin panel --> </div>
<!-- rest of project site -->
</body>
</html>
Maybe itd help if you show us the structure of the elements, but from the definition of "Remove" in Jquery, it should remove the element, its children, all events and any data associated to it.
Is div.panel__inner located inside your body tag? I see that you are doing a remove on the div, but prepending the data to $('body'). Can you remove the body contents itself?
精彩评论