您好,如何在 asp treeview 中有条件地禁用复选框?
例如,如果应用程序用户没有某个权限,则在权限树中禁用该权限条目复选框。
这就是我要找的,这是 winform 应用程序中的等效物(文本呈灰色的复选框被禁用):
我看到其他解决方案截获并忽略了复选框上的单击事件。 我更喜欢将复选框简单设置为禁用的解决方案。
我正在寻找使用 C# 解决方案,但也可以接受使用 C# / Javascript 解决方案。
谢谢!
您好,如何在 asp treeview 中有条件地禁用复选框?
例如,如果应用程序用户没有某个权限,则在权限树中禁用该权限条目复选框。
这就是我要找的,这是 winform 应用程序中的等效物(文本呈灰色的复选框被禁用):
我看到其他解决方案截获并忽略了复选框上的单击事件。 我更喜欢将复选框简单设置为禁用的解决方案。
我正在寻找使用 C# 解决方案,但也可以接受使用 C# / Javascript 解决方案。
谢谢!
好的,我找到了一个相当简洁的解决方案:
在代码后台:
TreeNode newNode = new TreeNode(permission.ToString());
newNode.SelectAction = TreeNodeSelectAction.None; // no Link
if (shouldDisableCheckbox)
{
// Set a class so disabled nodes can be formatted thru CSS
// and be identifiable as disabled in Javascript.
newNode.Text = "<span class=disabledTreeviewNode>" + newNode.Text +"</span>";
}
nodes.Add (newNode);
// Called via a startup script created in Code Behind.
// Disables all treeview checkboxes that have a text with a class=disabledTreeviewNode.
// treeviewID is the ClientID of the treeView
function DisableCheckBoxes(treeviewID)
{
TREEVIEW_ID = treeviewID;
var treeView = document.getElementById(TREEVIEW_ID);
if (treeView)
{
var childCheckBoxes = treeView.getElementsByTagName("input");
for (var i = 0; i < childCheckBoxes.length; i++)
{
var textSpan = GetCheckBoxTextSpan(childCheckBoxes[i]);
if (textSpan.firstChild)
if (textSpan.firstChild.className == "disabledTreeviewNode")
childCheckBoxes[i].disabled = true;
}
}
}
function GetCheckBoxTextSpan(checkBox)
{
// Set label text to node name
var parentDiv = checkBox.parentNode;
var nodeSpan = parentDiv.getElementsByTagName("span");
return nodeSpan[0];
}
很遗憾,我没有足够的声望来直接评论zukanta的答案,这有点麻烦,但我不得不修改javascript使其正常工作:
if (textSpan.firstChild)
if (textSpan.className == "disabledTreeviewNode")
childCheckBoxes[i].disabled = true;
即用textSpan.ClassName替换textSpan.firstChild.ClassName
还值得指出的是,除非您要处理的树形视图中的所有树节点都有一个
<span></span>
if (textSpan.firstChild)
并且不会处理任何后续节点。
我通过给所有我不想禁用的树节点添加一个class=enabledTreeviewNode的span来解决了这个问题。
你也可以在JavaScript中处理异常,我猜。
希望这能帮助那些以后遇到这个(非常好的)解决方案的人。
OP正在寻找条件禁用,但我只想使用TreeView来显示历史审计数据,记录项目何时被打开。我的页面上所有复选框都应该被禁用。我花了一些时间才找到这个优雅的jQuery解决方案。我希望它能帮助任何遇到类似问题的人。
将下面的代码添加到您的脚本部分。由于所有输入框都将被禁用,因此无需对您的代码进行任何更改。
<script type="text/javascript">
$(document).ready(function () {
$("input:checkbox").each(function () {
$(this).prop('disabled', true);
});
});
</script>
if (textSpan.firstChild.className == "disabledTreeviewNode")
这一行改为if (textSpan.className == "disabledTreeviewNode" || textSpan.firstChild.className == "disabledTreeviewNode")
,否则我需要运行JS 2次才能使其生效。在第一次调用中,textSpan.className =="disabledTreeviewNode"
是true
,随后对textSpan.firstChild.className =="disabledTreeviewNode"
的调用使你的代码生效了。我不是100%确定自己是否理解了,但检查这两个条件让它正常工作了。 - atconwayjQuery
完成了所有这些JavaScript
操作:http://stackoverflow.com/questions/18858842/convert-scanning-for-classname-javascript-block-to-use-jquery - atconway$(document).ready
jQuery事件和回发结束事件,并摆脱那些令人讨厌的服务器端代码。 - Sue Maurizio