JQuery gets examples of dynamically generated elements

  • 2020-03-30 03:21:08
  • OfStack

Description of requirements: data can be dynamically added on the page, such as table, click the button to dynamically add rows. Or page
When the table data is loaded, it is obtained from the background through ajax. And then we want to get some of these values, how do we get them?

If you want to get by an event such as click,mouseover, etc., you can use the live() method
 
$(".button").live("click",function(){ 
console.info($("#mytd").html()); 
}) 

If it's not through an event, we'll get the value or do something else when the page loads

The live() method doesn't work because we can't pass in an event.

For example, the following code:
 
<body> 
<table id="tab" border="1" width="30%"> 

</table> 
</body> 
<script type="text/javascript"> 
$(function() { 
$.post("admin/UserForumthemeBabygrowupFrontList.do",{},function(data){ 
console.info(data.table); 
$("#tab").append(data.table); 
}) 

alert($("#mytd").html()); //Get the value
}); 
</script> 

The above code is simply to add the value returned from the background by post to < Table> In the

Background return data is < Tr> < Td id = 'mytd > Beijing < / td> < Td> Shenzhen < / td> < / tr> And we're going to get the value of id mytd after post,

At this point is not available, we can observe the problem from the browser:
< img SRC = "border = 0 / / files.jb51.net/file_images/article/201406/20140615111818.gif? 2014515111944 ">  
From the above, you can see that the data has not been loaded and the console has not printed the information at the time of alert, so the data cannot be retrieved at this time.

Using the ajaxComplete() method to run the code to be executed when the request is completed, we change it to the following:
 
$(function() { 
$.post("admin/UserForumthemeBabygrowupFrontList.do",{},function(data){ 
console.info(data.table); 
$("#tab").append(data.table); 
}) 
$("#tab").ajaxComplete(function(){ //Execute when the request is complete
alert($("#mytd").html()); 
}) 
}); 

< img border = 0 SRC = "file:///C:/Documents%20and%20Settings/Administrator/Local%20Settings/Temporary%20Internet%20Files/Content.IE5/Y96A18VM/20140615112011 [1]. GIF" >  
At this point, the page is loaded when fetched again.

Related articles: