Home  >  Article  >  Web Front-end  >  js获取TreeView控件选中节点的Text和Value值的方法_javascript技巧

js获取TreeView控件选中节点的Text和Value值的方法_javascript技巧

WBOY
WBOYOriginal
2016-05-16 17:48:041438browse

在实际项目中,遇到一个问题,首先弹出一个新窗口,新窗口中放了一个TreeView控件,TreeView控件的数据绑定在我的上一篇随笔(TreeView绑定XML数据源C#代码示例)中有讲到,现在要解决的是,如何单击TreeView中一个节点,返回Text和Value到父页面并关闭该新窗口。
首先,在后台代码中为TreeView添加属性onclick以支持TreeView的客户端事件,代码如下:

复制代码 代码如下:

if (!IsPostBack)
{
TreeView1.Attributes.Add("onclick", "ReturnValue()");//ReturnValue为javascript函数
BindTreeView();
}

那现在就要解决如何通过js获得TreeView中被选中的那个节点,脚本如下:
复制代码 代码如下:

function ReturnValue() {
var objNode = event.srcElement;
var unitid = event.srcElement.href;
if (objNode.tagName != "SPAN") {
return;
}
window.opener.document.getElementById("txtUnit").value = objNode.getAttribute("innerHtml");
window.opener.document.getElementById("txtUnitID").value = unitid;
window.close();
}

其实这里用了点小花招,因为我实在不知道在哪个属性里能获得绑定给TreeView的ValueField的值,所以,Value值我一并绑给了NavigateUrl,也就是写黄色部分代码的原因,Html代码如下:
复制代码 代码如下:







红色部分代码是用来获取TreeView上显示文字的,因为如果你去查看源文件的话,你会发现,TreeView的Text属性值被放在了SPAN中。
绿色部分代码是用来回填父页面的,但是要注意的是,"txtUnit"必须是客户端控件,因为如果是服务器端控件,弹窗在编译时会报不存在该控件。
这样,我需要的功能就实现了!另外,有人可能会说,父页面中用来装载回填值的是客户端控件,那如果要在服务器事件中使用怎么办?也很简单,C#代码如下:
Request.Form["txtUnit"].ToString();
但是要注意了,这里的"txtUnit"可不是控件ID,而是name属性了!
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn