需求:读取路径配置中的相对路径获取对应的子文件夹及其子文件并形成树形结构,加载xml文件,输入搜索关键字匹配xml里面的value节点的值对应的contact值的集合并进行搜索
例如:输入b,找到xml里面的文本节点等于b的value节点,并找到对应的contact节点获取对应的文本节点值,结果是3,4,最后匹配的就是文件名包含b或3或4的所有文件并高亮显示
1、页面布局
<div><a href="javascript:;" class="easyui-linkbutton">路径配置</a><input type="text" value="/Images" id="root_path" /><a id="btn_loadxml" href="javascript:;" class="easyui-linkbutton">加载xml</a><input type="text" value="/FilesHelpManager/keyword_config.xml" id="xml_path" /><a id="btn_search" href="javascript:;" class="easyui-linkbutton">搜索</a><input type="text" value="" id="txt_search" />
</div>
<div><ul id="path_tree" checkbox="true"></ul>
</div>
<%--右键下载按钮--%>
<div id="right_download" class="easyui-menu" style="width: 120px;"><div onclick="Download();">Download</div>
</div>
2、初始化并加载路径配置下的所有文件夹及其子文件并形成树形目录
var $path_tree;$(function () {$path_tree = $('#path_tree');//加载指定文件夹形成树形目录
loadTreeDirectorys();//点击搜索$("#btn_search").on("click", tree_search);//点击加载xml$("#btn_loadxml").on("click", LoadXml);
});//加载指定文件夹形成树形目录
function loadTreeDirectorys() {//页面初始化时加载页面的树形菜单$.post("/Handler/FilesHelpManager/FilesHelpHandler.ashx",{"action": "GetFileTree","root_path": $("#root_path").val()//根目录位置
},function (json) {$("#path_tree").tree({data: json,onContextMenu: function (e, node) {e.preventDefault();$(this).tree('select', node.target);//console.log(node.target);$('#right_download').menu('show', {left: e.pageX,top: e.pageY});}});}, "json");
}
3、后台读取子文件夹及其子文件
HttpRequest request;
HttpResponse response;
public void ProcessRequest(HttpContext context)
{request = context.Request;response = context.Response;context.Response.Buffer = true;context.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1);context.Response.AddHeader("pragma", "no-cache");context.Response.AddHeader("cache-control", "");context.Response.CacheControl = "no-cache";context.Response.ContentType = "text/plain";string action = context.Request["action"];System.Reflection.MethodInfo methodinfo = this.GetType().GetMethod(action);methodinfo.Invoke(this, null);
}public void GetFileTree()
{StringBuilder strResult = new StringBuilder();string root_path = request.Params["root_path"];string root_path_absolute = HttpContext.Current.Server.MapPath(root_path);strResult.Append("[" GetFilesTree(root_path_absolute,root_path) "]");response.Write(strResult.ToString());
}/// <summary>
/// 获取指定文件夹里的子文件夹和子文件(包括嵌套的)
/// </summary>
/// <param name="root_path_absolute">绝对路径</param>
/// <param name="root_path">相对于网站根目录路径</param>
/// <returns></returns>
private string GetFilesTree(string root_path_absolute,string root_path)
{StringBuilder strResult = new StringBuilder();string[] dirs = Directory.GetDirectories(root_path_absolute);dirs.ToList().ForEach(dir =>{string dir_name = dir.Substring(dir.LastIndexOf('\\') 1);string dir_path = root_path "/" dir_name;if (strResult.Length > 0){strResult.Append(",");}string strDirs = "{\"text\":\"" dir_name "\",\"state\":\"closed\",\"attributes\":{\"dir_src\":\"" dir_path "\"},\"children\":[" GetFilesTree(dir, dir_path) "]}";strResult.Append(strDirs);});string[] files = Directory.GetFiles(root_path_absolute);files.ToList().ForEach(file =>{string filename = file.Substring(file.LastIndexOf('\\') 1);if (strResult.Length > 0){strResult.Append(",");}string strFiles = "{\"text\":\"" filename "\",\"attributes\":{\"file_src\":\"" root_path "/" filename "\"}}";strResult.Append(strFiles);});return strResult.ToString();
}
4、点击加载xml文件(jQuery加载)
定义全局变量用来接收读取的xml文件内容的值
//循环树形菜单text然后匹配下面数组 判断是否包含
var target_obj = [{ keyword: "a", contact_arr: ["1", "2"] }];
//加载xml
function LoadXml() {$.ajax({type: "get",url: $("#xml_path").val(),//这里通过设置url属性来获取xmldataType: "xml",timeout: 1000, //设定超时cache: false, //禁用缓存success: function (xml) {//这里是解析xml//清空数组对象target_obj = [];$(xml).find("keyword").each(function (i, item) {var $this = $(this);var $value = $this.children("value"); //获取value节点var $contacts = $this.children("contact"); //获取contact节点//console.log($value); console.log($contacts);// return;//要准备压入target_obj数组中的对象var arr_obj = {};arr_obj.keyword = $value.text().trim();arr_obj.contact_arr = new Array();//循环contact节点$.each($contacts, function (j, contact) {arr_obj.contact_arr.push($(contact).text().trim());});target_obj.push(arr_obj);});//console.log(target_obj);
}});
}
5、输入搜索字符串并点击搜索
//树形菜单查找
function tree_search() {//清空之前的所有选项并收缩
clearAllSelect();var search_text = $("#txt_search").val().trim();if (search_text.length <= 0) return;//输入空字符串不执行任何操作//要循环的匹配数组var target_arr = [];target_arr.push(search_text);$.each(target_obj, function (index,item) {if (item.keyword == search_text) {$.each(item.contact_arr, function (index1, item1) {if (item1.length > 0) target_arr.push(item1)});}}); //console.log(target_arr.join(","));var parentNodes = $path_tree.tree('getRoots'); //得到tree顶级nodevar childrens;//子节点//循环根节点$.each(parentNodes, function (index, parentNode) {childrens = $path_tree.tree('getChildren', parentNode.target);//获取顶级node下所有子节点if (childrens.length>0) {//如果有子节点//循环所有子节点$.each(childrens, function (child_index, child) {//循环匹配数组$.each(target_arr, function (arr_index, arr_item) {if (child.text.indexOf(arr_item) >= 0) {selectNode(child);//选中当前节点expandParent(child);//打开所有父节点return;//跳出第一层循环
}})});} else {//直接匹配根节点的text//循环匹配数组$.each(target_arr, function (arr_index, arr_item) {if (parentNode.text.indexOf(arr_item) >= 0) {selectNode(parentNode);//选中当前节点expandParent(parentNode);//打开所有父节点return;//跳出第一层循环
}})}});
}de节点
function selectNode(node) {//console.log(node.target);//.tree-node-selected$(node.target).addClass("tree-node-selected");$path_tree.tree('check', node.target);//check select
}
//取消选中node节点
function unSelectNode(node) {$(node.target).removeClass("tree-node-selected");$path_tree.tree('uncheck', node.target);//check select
}
//展开子节点对应的所有父节点
function expandParent(node) {var parent = node;var t = true;do {parent = $path_tree.tree('getParent', parent.target); //获取此节点父节点if (parent) { //如果存在t = true;$path_tree.tree('expand', parent.target);} else {t = false;}} while (t);
}
//清空所有选择项 收缩所有节点
function clearAllSelect() {var parentNodes = $path_tree.tree('getRoots'); //得到tree顶级nodevar childrens;//子节点//循环根节点$.each(parentNodes, function (index, parentNode) {childrens = $path_tree.tree('getChildren', parentNode.target);//获取顶级node下所有子节点if (childrens.length > 0) {//如果有子节点//循环所有子节点$.each(childrens, function (child_index, child) {unSelectNode(child);//取消选中当前节点
});} else {//直接匹配根节点的textunSelectNode(parentNode);//取消选中当前节点
}});//收缩所有$path_tree.tree('collapseAll');
}
6、右键下载文件
//右键点击下载
function Download() {var node = $path_tree.tree('getSelected'); //console.log(node);var url = node.attributes.file_src;var el = document.createElement("a");document.body.appendChild(el);el.href = url; //url 是你得到的连接el.target = '_self'; //指定在新窗口打开el.setAttribute("download", "");//指示不解析 只下载 ie不兼容
el.click();document.body.removeChild(el);
}
示例:输入a,点击查询
输入h,点击查询
更多专业前端知识,请上 【猿2048】www.mk2048.com