Resolving Problems with jQuery and Unordered List Loading -
i'm building simplistic unordered list tree in xhtml multiple levels deep. way works click parent node, , uses jquery .load() api make ajax call server see if node has children. if does, inserts nodes inside. when click parent link again, .remove() remove children.
everything works fine in safari, chrome, , firefox. in ie6, ie7, ie8, , opera, it's breaking.
in ie's, code works when expanding parents show children. when click parents hide children again .remove(), it's going children , doing remove of children, rather itself.
in opera, code expands moves margins on expanded. then, on remove, exhibits same problem ies.
what causing strangeness?
sample posted here: http://volomike.com/downloads/sample1.tar.gz
ok, volomike! looked @ code there few problems:
first, when use load
, doesn't replace selected node, replaces contents.
so, calling load on li
returning same li
in ajax result. subsequently, getting this:
<li id="node-7"> <li id="node-7"> ...
also, closing 2 </ul>
tags in ajax.php
line 38
instead of 1 ul
, 1 li
.
so, if fix things should start working. said, approach doing totally differently. hope helps out:
html
<ul id="tree"> <li id="node-1"><a href="#">cat 1</a></li> <li id="node-7"><a href="#">cat 7</a></li> </ul>
php
// you'll have write code, format: // push each row of `mysql_fetch_array` new array $ret = array( array('2', 'cat 2'), array('3', 'cat 3') ); // return browser this: echo json_encode( $ret );
js/jquery
$(function(){ $("ul#tree li a").live('click', function(e){ e.preventdefault(); var $li = $(this).closest('li'); if( $li.find('ul').length ){ // remove ul if exists $li.find('ul').remove(); } else { // id var id = $li[0].id.replace('node-',''); // json id $.getjson('/ajax.php', { id: id }, function( data ){ // if data not empty , array if(data && $.isarray( data )){ // build our ul var $ul = $("<ul></ul>"); // loop through our data $.each(data, function(){ // build li, use `text()` escape text // append ul $('<li id="node-' + this[0] + '"><a href="#"></a></li>') .find('a').text(this[1]) .end().appendto($ul); }); // finally, add ul our li $ul.appendto($li); } }); } }); });
Comments
Post a Comment