2

Page 1

<html>
<head>
<script src="jquery-1.8.3.js" type="text/javascript"></script>
</head></head>
<body><div id="main"></div> </body>
<script>$('div[id=main]').load('page2.php')
$('span[id*=temp]').on('click',function(){
alert(this.id); }); //this block of code not working!!
</script>
</html>

Page 2

<div>
<span id="temp">
this is demo
</span>
</div>

Basically i want to load page2 again in main div when tag is clicked but am not able to fetch the id of the tag in page one,script of page1 not working for page 2 items or tags

dissectorz
  • 55
  • 7

2 Answers2

1

You are trying to bind the event right after the AJAX call, so the element doesn't exist yet. The call is asynchronous, so it doesn't stop the code execution to wait for the response.

Either bind the element after the content has loaded, using the success callback of the load method:

$('div#main').load('page2.php', function(){
  $('span[id*=temp]').on('click', function(){
    alert(this.id);
  });
});

or use a delegate to bind the event to the parent element:

$('div#main').load('page2.php');
$('div#main').on('click', 'span[id*=temp]', function(){
  alert(this.id);
});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

Because you need to specify the parent selector to taking into account the elements created dynamicaly.

Exemple :

$("#main").on('click', 'span[id*="temp"]', function() {alert('Handler is working!');})

Here is a good related question : jQuery 1.7 on() and off() methods for dynamic elements

Community
  • 1
  • 1
sdespont
  • 13,915
  • 9
  • 56
  • 97