'overriding' javascript function

2019-05-18 18:32发布

I need to add some validations before the user navigates away via an ASP.NET Menu.

I noticed that the items are rendered to use a javascript function called Menu_Key

<td id="ctl00_MainMenun1" onmouseover="Menu_HoverStatic(this)" onmouseout="Menu_Unhover(this)" onkeyup="Menu_Key(this)">

I there a way to override that function and have the menu execute one of mine, from which I could validate what I need and then call the original?

5条回答
家丑人穷心不美
2楼-- · 2019-05-18 18:55

Above solution is a valid one, but in common case redefinition can be done in a bit more flexible way

var originalMenu_Key = Menu_Key;

Menu_Key = function(t) { 
   // do your validations here

   if ( /* everything validated */ ) {
     return originalMenu_Key.apply(this,argumets);
   }
};

In such case , any changes in function signature , will not break wrapping logic.

查看更多
闹够了就滚
3楼-- · 2019-05-18 18:57

Just redefine the function at the bottom of the page (technically after the initial declaration).

查看更多
smile是对你的礼貌
4楼-- · 2019-05-18 18:58

Redefine the function after it was initially defined, but keep track of it in a var so that you can call it later. You would effectively be renaming the original Menu_Key function.

var originalMenu_Key = Menu_Key;

Menu_Key = function(t) { 
   // do your validations here

   if ( /* everything validated */ ) {
     originalMenu_Key (t);
   }
};
查看更多
倾城 Initia
5楼-- · 2019-05-18 19:01

You have more than one way to do this. Depend of what you want.

If you want a function to run before the existing one then add this.

<td id="ctl00_MainMenun1" onmouseover="Menu_HoverStatic(this)" 
onmouseout="Menu_Unhover(this)" onkeyup="my_Function(); Menu_Key(this);">

If you want to run the second function conditionally then add this

<td id="ctl00_MainMenun1" onmouseover="Menu_HoverStatic(this)"
onmouseout="Menu_Unhover(this)" onkeyup="my_Function(this);">


function my_Function(sender)
{
  if(valid)
     Menu_Key(sender);
}
查看更多
Bombasti
6楼-- · 2019-05-18 19:02

Use the js code:

    $(document).ready(function () {

    $("td").mouseover(function(){
          alert('MouseOver validation content goes here.');
        }).mouseout(function(){
          alert('MouseOut  validation content goes here.');
});

hth!

查看更多
登录 后发表回答