尝试内联编写javascript函数:dons'不起作用

Trying to write a javascript function inline: doesn't work

本文关键字:dons 不起作用 函数 javascript      更新时间:2023-09-26

我试图以内联的方式写下这个javascript函数:

function WhichKeyPress(e) {
 if (!e) {
  //if the browser did not pass the event 
  //information to the function, 
  //we will have to obtain it from the 
  //event register
  if (window.event) {
       //Internet Explorer
        e = window.event;
     } else {
       //total failure, we have no 
      //way of referencing the event
       return;
     }
   }
   if (typeof (e.keyCode) == 'number') {
      //DOM
      e = e.keyCode;
    } else if (typeof (e.which) == 'number') {
      //NS 4 compatible
      e = e.which;
    } else if (typeof (e.charCode) == 'number') {
     //also NS 6+, Mozilla 0.9+
      e = e.charCode;
    } else {
      //total failure, we have no way of obtaining the key code
      return;
    }
}

它变成了这样:

Me.Attributes.Add("onkeydown","var evt; if(!e){ evt = window.event;}else{return;} if(typeof(evt.keyCode == 'number'){//do something}else if....."}

事情还在继续。不用说它不起作用。我尝试过其他内联javascript函数,比如:

Me.Attributes.Add("onkeydown","if(event.keyCode == 13){return event.keyCode = 9;} ")

它有效。但如果我这样做:

Me.Attributes.Add("onkeydown","var cod = event.keyCode; if(cod == 13){return cod = 9;})

这行不通。

我真的可以内联编写一个完整的javascript函数吗?在声明变量和其他一切的情况下?

编辑:我已经阅读了@millimoose提供的链接,我正试图在vs2005中的dll中使用一个外部.js文件,但没有成功。到目前为止,我还没有做什么:

1) 在dll解决方案中用js文件创建了一个"Scripts"文件夹。

2) 将生成操作设置为"EmbeddedResource"

3) 覆盖我的OnPreRender方法如下:

Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
                Page.ClientScript.RegisterClientScriptResource(Me.GetType(), "webControlesUES.Scripts.EnterToTab.js")
                Page.ClientScript.RegisterStartupScript(Me.GetType(), "EnterToTab", "teste()", True)
End Sub

4) 在我的渲染方法上,我添加了以下内容:

Me.Attributes.Remove("onkeydown")
Me.Attributes.Add("onkeydown", " teste();")
If Me.TextMode = Web.UI.WebControls.TextBoxMode.MultiLine Then
     Me.Attributes.Remove("onkeydown")
End If

5) 在我的AssemblyInfo.vb 上添加了这个

<Assembly: System.Web.UI.WebResource("webControlesUES.Scripts.EnterToTab.js", "application/x-javascript")>

6) 构建了解决方案并添加了用于测试的dll。

但它不起作用。我是不是忘了什么?

事件对象也作为内联代码的参数发送到函数,但由于没有任何函数声明,因此需要从arguments集合中获取它,而不是作为命名参数。

示例:

Me.Attributes.Add("onkeydown","var e=arguments[0];if(e.keyCode == 13){ alert('enter'); }");