tags:

views:

37

answers:

2

I am populating a <div> with the html() function, after a link is clicked. Basically, I don't want the page to refresh, but put stuff inside the <div>.

That works fine. However, I am passing a link into the <div>, and trying to select that too! It literally takes me to a different page, rather than populating the next <div>, as I expected.

<script type="text/javascript">
$(document).ready(function() {

  $(".link1").click(function(){ $("#div1").html("<a href='#' class='link2'>click here</a>"); return false; });
  $(".link2").click(function(){ $("#div2").html("Just Text"); return false; });

}); 
</script>

<div id="div1"></div>
<div id="div2"></div>
+2  A: 

You probably want to use live():

$(function() {
  $("a.ink1").live("click", function() {
    $("#div1").html("<a href='#' class='link2'>Click here</a>');
    return false;
  });
  $("a.link2").live("click", function() {
    $("#div2").html("Just text");
    return false;
  });
});

The reason is that when you bind an event with click() it does so on elements that exist at the time not elements you create later. That's what live() is for.

cletus
shouldn't that be `$("a.link1").live( "click", function() {...` and `$("a.link2").live( "click", function() {...`?
beggs
@beggs: yes it should. My bad. Thanks for pointing that out.
cletus
A: 

How about:

<script type="text/javascript">
$(document).ready(function() {

  $(".link1").click(function(){ $("#div1").html("<a href='#' class='link2'>click here</a>"); renderlink2(); return false; });
  renderlink2();

}); 

function renderlink2(){
  $(".link2").click(function(){ $("#div2").html("Just Text"); return false; });
}
</script>

<div id="div1"></div>
<div id="div2"></div>
thephpdeveloper