Reputation: 1068
So I have a script like this
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$("a[href*='http://']:not([href*='"+location.hostname+"'])").attr("target","_blank");
$("a[target!='_blank'][target!='_top']").click(function(){
var url=$(this).attr("href")+'?jquery=1';
ajaxpage(url,'actualcontent');
window.location.hash=$(this).attr("href");
return false;
});
});
</script>
and it works great. It means all my links load dynamically within the DIV - awesome. But, the links loaded in those div, don't load dynamically when clicked. and if I include this script in it, it still doesn't work. And on a similar note, is there a way of making javascript in pages, which have been loaded dynamically, work? Without including it in the original header?
Thanks.
Upvotes: 2
Views: 554
Reputation: 21680
Use .delegate()
// Don't need to put this in a $(document).ready() callback.
$(document).delegate("a[target!='_blank'][target!='_top']", "click", function(e){
var url=$(this).attr("href")+'?jquery=1';
ajaxpage(url,'actualcontent');
window.location.hash=$(this).attr("href");
e.preventDefault();
return false;
});
$(document).delegate("a[href*='http://']:not([href*='"+location.hostname+"'])", "click", function(){
// lazy attr setting, reduces query cost
$(this).attr("target", "_blank")
});
Upvotes: 0
Reputation: 207501
Not sure what your problem is. You are saying that the links that are added after this function rn do not use this function? hint, you need to rescan the page to update the links in that div OR you can avoid that and use live().
Upvotes: 2
Reputation: 630379
Disclaimer: To use this solution, you'll need to upgrade to jQuery 1.3 or jQuery 1.4+
(But you should, there are many performance improvements and bug fixes since 1.2.6)
Instead of .click()
you can use .live()
here, like this:
$("a[target!='_blank'][target!='_top']").live('click', function(){
.live()
works on dynamically added elements as well, since it's listening for the bubbling click
event at document
, rather than being a handler on the element itself.
Upvotes: 2