我正在开发一个 ASP 网站,在该网站的 HEAD 部分使用 Javascript 代码。 我正在尝试实现自己的上下文菜单,因此我在本节中编写了它的逻辑。我的代码如下:
function fileGridGrouping_ContextMenu(s, e) {
if(e.objectType != "row") return;
fileGridGrouping.SetFocusedRowIndex(e.index);
lastFileId = "<%# fileGridGrouping.GetRowValues(fileGridGrouping.FocusedRowIndex, "ID").ToString() %>";
}
如您所见,我还在后台调用了一些 C# 代码,用于获取所选行的 ID。以下代码抛出异常,如果 FocusedRowIndex 未初始化,则这是正常的:
出于测试目的,我决定不再使用 FocusedRowIndex,但始终获取第一行:
function fileGridGrouping_ContextMenu(s, e) {
if(e.objectType != "row") return;
fileGridGrouping.SetFocusedRowIndex(e.index);
lastFileId = "<%# fileGridGrouping.GetRowValues(0, "ID").ToString() %>";
}
此代码没有抛出异常,这确实证明问题来自 FocusedRowIndex 未初始化(因此设置为 -1)。够好了!我决定轻松修复它:
function fileGridGrouping_ContextMenu(s, e) {
if(e.objectType != "row") return;
fileGridGrouping.SetFocusedRowIndex(e.index);
if ("<%# fileGridGrouping.FocusedRowIndex %>" <= 0) return;
lastFileId = "<%# fileGridGrouping.GetRowValues(0, "ID").ToString() %>";
}
但是,令人惊讶的是,在完全相同的位置抛出了相同的异常。 作为最后一次尝试了解究竟发生了什么,我决定评论罪魁祸首:
function fileGridGrouping_ContextMenu(s, e) {
if(e.objectType != "row") return;
fileGridGrouping.SetFocusedRowIndex(e.index);
if ("<%# fileGridGrouping.FocusedRowIndex %>" <= 0) return;
//lastFileId = "<%# fileGridGrouping.GetRowValues(fileGridGrouping.FocusedRowIndex, "ID").ToString() %>";
}
现在这真是太奇怪了:
注释行抛出异常,就好像注释代码实际上是由网站运行的一样。我尝试重新启动 Visual Studio,从头开始重建所有内容,但同样的事情一次又一次发生。
更奇怪的是,所有这些代码都是在实际发生任何点击之前运行的,但在页面加载时运行。当右键单击页面中的表时,应该调用函数 fileGridGrouping_ContextMenu() ,但此代码是在实际发生任何事情之前运行的。我猜有某种编译或类似的事情正在发生?
我不知道发生了什么,也不知道如何解决它。
编辑:我现在通过更改大部分代码解决了这个问题。事实证明我没有使用最好的功能来完成我想要的事情。哎呀。感谢所有帮助过我的人! 这是工作代码:
function fileGridGrouping_ContextMenu(s, e) {
if(e.objectType != "row") return;
fileGridGrouping.SetFocusedRowIndex(e.index);
fileGridGrouping.GetRowValues(fileGridGrouping.GetFocusedRowIndex(), "ID", OnGetRowValues);
}
function OnGetRowValues(value) {
lastFileId = value;
}
最佳答案
这里有一些不正确嵌套的引号:
"<%# fileGridGrouping.GetRowValues(fileGridGrouping.FocusedRowIndex, "ID").ToString() %>";
// See the syntax highlighting here ^
将该行替换为:
'<%# fileGridGrouping.GetRowValues(fileGridGrouping.FocusedRowIndex, "ID").ToString() %>';
(注意最后一行中的单引号 ('))
当该行被注释时,您仍然收到错误的原因是这些 block 中的任何代码:<%# %>
在服务器端运行。它基本上不关心前面的 JavaScript 注释。
关于javascript - ASP.Net Javascript 代码抛出奇怪的异常(即使有注释!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26461744/