0

I have a simple code like:

<html>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<body>
<a href="#" class="plink">Click me</a>

<div class="cnt">

</div>
<script>
$(document).ready(function(){
   $(".plink").click(function(){
     alert("A");
   });

$.ajax({
            url: 'do.php?a=getinfo',                        
            type: 'POST',
            success: function(result) {
                $(".cnt").html(result);
            }
});
});
</script>
</body>
</html>

From ajax query I get this:

<a href="#" class="plink">Click me 2</a>

The problem is that when I click on a link (Click me 2) that I get from ajax query, assigned for this link event doesn't work, i.e. alert("A") doesn't show. So, is there any way to solve this problem?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Evgeny
  • 95
  • 6
  • and [Events triggered by dynamically generated element are not captured by event handler](http://stackoverflow.com/q/12829963/218196) – Felix Kling Feb 15 '14 at 20:49
  • Since the answers fail to get the point across (IMO): Have a look at [event delegation](http://learn.jquery.com/events/event-delegation/). – Felix Kling Feb 15 '14 at 20:52

2 Answers2

0

.click()is not bindable with dynamic elements. Try this,

$("body").on("click",".plink",function(e){
     alert("A");
});

else

$(".plink").live(function(e){
         alert("A");
});
Subash Selvaraj
  • 3,385
  • 1
  • 14
  • 17
  • 1
    .live() is deprecated in newest versions of jQuery. See the docs https://api.jquery.com/live/ – melvas Feb 15 '14 at 20:53
  • @Evgeny: Make sure you understand *why*. Have a look at this more elaborated answer: http://stackoverflow.com/a/12830031/218196 and follow the links. – Felix Kling Feb 15 '14 at 20:55
0

New element from your ajax result has no binded click action. Try to use this:

$(document).on('click', '.plink', function(){ alert("A"); });

instead of:

$(".plink").click(function(){ alert("A"); });
melvas
  • 2,346
  • 25
  • 29