Hey all, This is more of a standards and structure question.
Consider this .load() scenario. I have a page that loads a second page into a div with the .load() function.
<html><head><title>My Page</title>
<script type='text/javascript' src='myfunctions.js'></script>
<head>
<body>
<a href='#' id='click_link'>Click Me</a><br>
<div id='target_container>
</div>
</body>
</html>
Where myfunction.js holds a click routine, that when #click_link is clicked it loads a page into #target_container. Now the page being loaded also needs access to myfunction.js. I could load it again and this actually seems to work, or I 开发者_如何学JAVAcould just put the javascript code that I need into the loaded page. This seems to work too.
My gripe, is that there has to be a better, more clean way of doing this. Am I going about this wrong? Or it this the only way to do this. I always thought javascript code should jailed inside <head></head>
and be beaten viciously if it tried to live outside of it.
I saw several posts on this, but none have a clear explanation on if this is the best way to handle this problem.
Please let me know. ~ Thanks
I think what you're looking for is jQuery's live()
method. With it, you can bind events to all current and future elements with the particular selector. This means you can leave all the javascript in the head and not have to worry about binding and rebinding every time you add new elements into the DOM.
You can write something like this in myfunctions.js
,
$('.new_or_old').live('mouseover', function(){
myFunction();
});
and every element with the class 'new_or_old' will call myFunction() on mouseover, even if it's inserted after the original page load.
精彩评论