How to make pre-collapsed TreeView with php/javascript

混江龙づ霸主 提交于 2019-12-24 16:33:59

问题


I've made a tree view using php/javascript. I just can't figure out how to make it pre-collapsed, on page load.

here is the code, come with the ideas.

<?php 

$query=mysql_query("SELECT tree_entry_lang.entry_id, tree_entry_lang.lang, tree_entry_lang.name, tree_entry.parent_entry_id FROM tree_entry,tree_entry_lang WHERE tree_entry.entry_id=tree_entry_lang.entry_id AND lang='eng'");
$numrows=mysql_num_rows($query);

if($numrows>0){
    echo "<ul >";
    while($row=mysql_fetch_assoc($query)){
        echo "<li><img src='..\images\expand.gif' class='collapsableTree' > ".$row['name'];
        getChildren($row['entry_id']);


    }
    echo "</ul>";


}
else echo "Empty base";

function getChildren($parent_id){

    $query=mysql_query("SELECT tree_entry_lang.entry_id, tree_entry_lang.lang, tree_entry_lang.name, tree_entry.parent_entry_id FROM tree_entry,tree_entry_lang WHERE tree_entry.entry_id=tree_entry_lang.entry_id AND parent_entry_id=".$parent_id);
$numrows=mysql_num_rows($query);

if($numrows>0){
    echo "<ul >";
    while($row=mysql_fetch_assoc($query)){
        echo "<li><img src='..\images\expand.gif' class='collapsableTree' > ".$row['name'];
        getChildren($row['entry_id']);


    }

            echo "</ul>";
            echo "</li>";

        }



}

And here is the jQuery part:

$('.collapsableTree').click(function () {

    $(this).parent().children().toggle();
    $(this).toggle();

});

As I've said, when the page loads, I need all my nodes to be closed. I presume some JavaScript function should be used, But I'm afraid I cant make one. Any solutions ?


回答1:


This isn't something supported by vanilla HTML/jQuery, you'll need to write a plugin to handle it. It's not a trivial task. I suggest taking a look at jstree, it's very full-featured and well documented.

EDIT

If all you're trying to do is hide the children, why not simply initialize them to display:none in CSS. Then show them when clicked. Otherwise, given your example above, make sure you wait until the DOM is ready before you try to bind the event handler by wrapping your statement in $(function(){...}):

$(function(){
    $('.collapsableTree').click(function () {
        $(this).parent().children().toggle();
        $(this).toggle();
    });
});



回答2:


Very simple using CSS. Add some classes to the elements.

<ul class="tree">
   <li class="node">
       <ul class="branch">

Then in css:

.tree.branch{display:none}


来源:https://stackoverflow.com/questions/15349533/how-to-make-pre-collapsed-treeview-with-php-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!