上下文
我有一个包含文件夹和文件的 TreeView :
附加信息
- 所有文件和文件夹都是可拖放的。
- 文件夹有
.pft-directory
通用类和#/folder1/folder2/etc
编号。 - 文件有
.pft-file
通用类和files/folder1/folder2/etc/fileName.ext
引用。 - 文件和空文件夹是
<li><a>text of file/folder</a><li>
. - !空文件夹还有
<ul><li><a>text of subfolder</a></li>...etc...</ul>
.
问题
每次拖放后,我都会更新文件夹的 ID 和文件的 href。显然,当文件夹不为空并且有多个子文件夹迭代时,它会变得更加复杂。我写了 2 次迭代(见下面的代码)。
问题
你能帮我写一个DOM递归读取函数吗?
代码
jquery :
//the first folder
ui.draggable.find('a.pft-directory:first').attr('id', $path_Ite1);
//inside the first folder...
ui.draggable.find('ul:first > li > a').each(function() {
var $this_Ite1 = $(this);
//if file, else folder
if ($this_Ite1.hasClass('pft-file')) {
$this_Ite1.attr('href', 'files' + $path_Ite1 + '/' + $this_Ite1.text());
}
else {
var $path_Ite2 = $path_Ite1 + '/' + $this_Ite1.text();
$this_Ite1.attr('id', $path_Ite2);
//inside the second folder...
$this_Ite1.parent().find('ul:first > li > a').each(function() {
var $this_Ite2 = $(this);
if ($this_Ite2.hasClass('pft-file')) {
$this_Ite2.attr('href', 'files' + $path_Ite2 + '/' + $this_Ite2.text());
}
else {
var $path_Ite3 = $path_Ite2 + '/' + $this_Ite2.text();
$this_Ite2.attr('id', $path_Ite3);
//inside the third folder etc...
}
});
}
});
最佳答案
就我个人而言,我无法在可拖动部分为您提供帮助,但关于递归函数,您可能会发现类似以下内容的内容很有用。
我还必须根据您提供的描述来假设您的 HTML 是什么样子(某些 HTML 在这些类型的问题中会非常方便)。
您可以在下面的 jsFiddle 中看到它的运行情况。 . (如果使用 Firefox,请选择“结果” Pane 中的所有内容,右键单击并查看选择源以查看更新的属性)
HTML:
<ul>
<li>
<a class="ptf-directory">Folder1</a>
<ul>
<li>
<a class="ptf-directory">Folder3</a>
<ul>
<li>
<a class="ptf-file">File4.txt</a>
</li>
</ul>
</li>
<li>
<a class="ptf-file">File1.txt</a>
</li>
</ul>
</li>
<li>
<a class="ptf-directory">Folder2</a>
</li>
<li>
<a class="ptf-file">File2.txt</a>
</li>
<li>
<a class="ptf-file">File3.txt</a>
</li>
</ul>
JQuery:
$(function(){
UpdateFolderItems($('ul:first'), '');
});
function UpdateFolderItems(folder, basePath)
{
// go through folder contents
folder.children('li').each(function(){
// get item
var item = $(this).children('a');
// generate new path for item
var newPath = basePath + '/' + item.text();
// if item is a folder
if (item.hasClass('ptf-directory'))
{
// update id on folder
item.attr('id', newPath);
// if folder content exists
var folderContent = $(this).children('ul:first');
if (folderContent.length > 0)
{
// update folder content
UpdateFolderItems(folderContent, newPath);
}
}
// if item is a file
else if (item.hasClass('ptf-file'))
{
// update href on file
item.attr('href', newPath);
}
});
}
关于javascript - 具有递归更新的 JavaScript 中的 TreeView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9019305/