好的,沃洛迈克!我查看了您的代码,发现有一些问题:
首先,当您使用load 时,它不会替换所选节点,而是替换其内容。
因此,您在 li 上调用 load 但在 AJAX 结果中返回相同的 li。随后,您将得到:
<li id="node-7">
<li id="node-7">
...
另外,您在ajax.php 行38 中使用两个</ul> 标签来关闭它,而不是一个ul 和一个li。
因此,如果您解决了这些问题,它应该会开始工作。也就是说,我会以完全不同的方式处理你正在做的事情。希望对您有所帮助:
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 to write the code, but get it into this format:
// Basically push each row of a `mysql_fetch_array` into a new array
$ret = array(
array('2', 'Cat 2'),
array('3', 'Cat 3')
);
// Then return it to the browser like 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 it exists
$li.find('ul').remove();
} else {
// Get the ID
var id = $li[0].id.replace('node-','');
// Get the JSON for that id
$.getJSON('/ajax.php', { id: id }, function( data ){
// If data is not empty and it is an array
if(data && $.isArray( data )){
// Build our UL
var $ul = $("<ul></ul>");
// Loop through our data
$.each(data, function(){
// Build an LI, use `text()` to properly escape text
// then append to the UL
$('<li id="node-' + this[0] + '"><a href="#"></a></li>')
.find('a').text(this[1])
.end().appendTo($ul);
});
// Finally, add the UL to our LI
$ul.appendTo($li);
}
});
}
});
});