2011-08-03 66 views
0

试图在jQuery中追加一些文本,将其转换为树型文件浏览器的链接。jQuery插入链接

的jQuery:

$(document).ready(function() 
{ 
    var listView = $('div.tree ul'); 

    $('div.tree > ul > li').each(
     function() { 
      var newLink = document.createElement('a'); 
      $('div.panel').append(newLink); 
      newLink.html($(this).children('span.cat').text()); 
      $(newLink).click(function(e) 
      { 
       alert($('div.tree span.cat:contains("'+$(this).text()+'")')); 
       e.preventDefault(); 
      }); 
     } 
    ); 
}); 

的内容是动态的PHP生成的,而是遵循这种结构:

<div class="tree"> 
    <ul> 
     <li> 
      <span class="cat">Category </span> 
     <ul> 
      <li> 
       <a href="example.jpg">example.jpg</a> 
      </li> 


///////////////etc//////// 

这给了错误"NewLink is not a function"

回答

1

改变这一行:

newLink.html($(this).children('span.cat').text()); 

这样:

$(newLink).html($(this).children('span.cat').text()); 

您试图调用一个DOM元素,它不具有html方法上html方法。将元素传递给一个jQuery对象,就像你已经做了附加一个点击事件处理程序一样,它应该可以正常工作。

+0

这就是它的欢呼声。 – BobFlemming

0
var newLink = document.createElement('a'); 

我想那是你出错的地方。这只是创建一个DOM元素,而不是DOM元素+ jQuery包装器(您需要在newLink上调用像html()这样的方法)。这是你怎么做的:

var newLink = $('a');