【问题标题】:Resolving Problems with jQuery and Unordered List Loading解决 jQuery 和无序列表加载问题
【发布时间】:2010-01-14 05:57:18
【问题描述】:

我正在用 XHTML 构建一个非常简单的无序列表树,它有多个层次。它的工作方式是单击父节点,然后它使用 jQuery .load() API 向服务器进行 AJAX 回调,以查看该节点是否有子节点。如果是这样,它会将这些节点插入其中。当您再次单击父链接时,它会执行 .remove() 删除子链接。

在 Safari、Chrome 和 FireFox 中一切正常。但在 IE6、IE7、IE8 和 Opera 中,它正在崩溃。

在 IE 中,代码在扩展父级以显示子级时起作用。但是当我点击父母再次使用 .remove() 隐藏孩子时,它会进入孩子并删除他们的孩子,而不是自己。

在 Opera 中,代码会扩展,但会在扩展时移动边距。然后,在删除时,它会出现与 IE 相同的问题。

什么可能导致这种奇怪?

此处发布示例:http://volomike.com/downloads/sample1.tar.gz

【问题讨论】:

  • 嘿伙计,你能发布你的 jQuery 代码吗?可能还有 HTML 标记的样本?
  • 现在附上示例链接。
  • 太棒了,我下载了你的样本。我会看看它,并尝试在今晚发布答案。谢谢!

标签: jquery list load unordered


【解决方案1】:

好的,沃洛迈克!我查看了您的代码,发现有一些问题:

首先,当您使用load 时,它不会替换所选节点,而是替换其内容

因此,您在 li 上调用 load 但在 AJAX 结果中返回相同的 li。随后,您将得到:

<li id="node-7">
   <li id="node-7">
      ...

另外,您在ajax.php38 中使用两个&lt;/ul&gt; 标签来关闭它,而不是一个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);
              }
          });
      }
   });
});

【讨论】:

  • 你在额外的 LI 节点和多个 UL 结尾上是对的。没有意识到这些,应该用 firebug 进行更好的调试。
  • 我也发现IE和Opera很奇怪,从$('#node-' + nClickID).html()返回大写的UL,所以必须使用.toLowerCase()。另外,不要检查
      因为在某些情况下 IE 会插入额外的参数。在 Javascript 中检查“
    猜你喜欢
    • 2012-11-16
    • 1970-01-01
    • 1970-01-01
    • 2011-07-21
    • 1970-01-01
    • 2022-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多