I was trying to show tree data with JQuery expand and collapse.
For example my database
Parent A has AA, AB, AC children
Parent AA has AAA, AAB, AAC
Parent AC has ACA, ACB, ACD
etc.
So I am using Recursion to show all the data from the database.
But I also need to declare the JQuery, so I am using the same Recursion code to generate the script
What I want to ask is, is there any way to use the Recursion one time to generate both things?, the data show inside the <body> tag, and JQuery declare at <head> tag.
Because I feel it will waste the memory to do same thing 2 times.
This is my <body> code
<?
$temp = "";
$parent = "";
$level = 0;
loadFolders($parent, $level, $temp);
function loadFolders($parent, $level, $temp){
$getLevelSql = mysql_query("select * from folders where parent='$parent' and level='$level'");
$level++;
while ($getLevelSqlRow = mysql_fetch_array($getLevelSql)){
$parentID = $getLevelSqlRow['id'];
$child = $getLevelSqlRow['child'];
$checkChild = mysql_query("select * from folders where parent='$parentID' and level='$level' ");
if (mysql_num_rows($checkChild)){
?>
<div class="level1 redFont" id="levelID<?echo $getLevelSqlRow['id'];?>">
<?echo "$child";?>
</div>
<div class="level2" id="childID<?echo $getLevelSqlRow['id'];?>">
<?
loadFolders($parentID, $level, $temp);
?>
</div>
<?
} else {
?>
<div><?echo "$child";?></div>
<?
}
}
}
?>
This is my <head> code
<script>
$(document).ready(function(){
<?
include "config.php";
$temp = "";
$parent = "";
$level = 0;
loadFolder($parent, $level, $temp);
function loadFolder($parent, $level, $temp){
$getLevelSql = mysql_query("select * from folders where parent='$parent' and level='$level'");
$level++;
while ($getLevelSqlRow = mysql_fetch_array($getLevelSql)){
$parentID = $getLevelSqlRow['id'];
$child = $getLevelSqlRow['child'];
$checkChild = mysql_query("select * from folders where parent='$parentID' and level='$level' ");
if (mysql_num_rows($checkChild)){
?>
$("#levelID<?echo $getLevelSqlRow['id'];?>").click(function(){
$("#childID<?echo $getLevelSqlRow['id'];?>").slideToggle("slow");
});
<?
loadFolder($parentID, $level, $temp);
?>
<?
}
}
}
?>
});
</script>
Thanks in advance
I haven’t tested this as I haven’t got data to do it but basically you really just need to use selectors in your jquery code to find the sub section from any of the click point.
I would nest the child element to make it easier. Something like this:
Then your jquery becomes something like this:
No need to loop twice and generate a hundred handlers..