如何使用键盘事件在命名函数上设置jquery事件?

时间:2018-04-04 21:08:16

标签: javascript jquery

我有这三个功能:

var triggerWynPopup = function(e) {
    ...
    e.preventDefault();
};

var closeWynPopup = function(e) {
    ...
    e.preventDefault();
};

var closeWynPopupKeyb = function(e) {
    if (e.keyCode === 27) {
        closeWynPopup();
    }
    e.preventDefault();
};

我这样称呼他们:

$btClose.on('click', closeWynPopup);
$wynPop.on('click', triggerWynPopup);
$document.on('keyup', closeWynPopupKeyb);

点击拨打closeWynPopuptriggerWynPopup时效果很酷,但是当我拨打$document.on('keyup', closeWynPopupKeyb);时会发出错误

  

未捕获的TypeError:无法读取未定义的属性'preventDefault'

可能是什么错误?

3 个答案:

答案 0 :(得分:3)

您错过了e

中的closeWynPopup()closeWynPopupKeyb
var closeWynPopupKeyb = function(e) {
    if (e.keyCode === 27) {
        closeWynPopup(e); // pass "e" here
    }
    e.preventDefault();
};

答案 1 :(得分:2)

if (e.keyCode === 27) {
    closeWynPopup(e);  //  here pass 'e'
}

由于您在closeWynPopup();中没有传递任何内容,因此e将在函数定义中取消定义,因此它会给出错误。

if (e.keyCode === 27) {
    closeWynPopup();  // passing undefined(in function e become 'undefined')
}

答案 2 :(得分:2)

该功能不需要特殊事件定义。你可以这样做。

function PostAdminData(body, method, url : string): IXMLDOMDocument;
type
   TMyPost = function (body, method, url: PChar; var OutData : PChar): integer; stdcall;
   TMyFree = function (Data  Pointer): integer; stdcall;
var
  hDll : THandle;
  MyPost : TMyPost;
  MyFree : TMyFree;
  dataString : string;
  returnData : PChar;
  returnLen : Integer;
begin
  hDll := LoadLibrary(PChar(ExtractFilePath(Application.ExeName) + 'TestDLL.DLL'));
  if hDll = 0 then begin
    Application.MessageBox('Unable to load TestDLL.DLL.', 'Error posting', MB_ICONERROR or MB_OK);
    Exit;
  end;
  try
    try
      MyPost := GetProcAddress(hDll, 'PostAdminDataViaDll');
      MyFree := GetProcAddress(hDll, 'FreeDataViaDll');
      if Assigned(MyPost) and Assigned(MyFree) then begin
        returnLen := MyPost(PChar(body), PChar(method), PChar(url), returnData);
        if returnLen > 0 then begin
          try
            SetString(dataString, returnData, returnLen);
          finally
            MyFree(returnData);
          end;
        end;
      end;
    finally
      FreeLibrary(hDll);
    end;
  except
  end;

  if dataString <> '' then begin
    try
      Result := CreateOleObject('Microsoft.XMLDOM') as IXMLDOMDocument;
      Result.async := False;
      Result.loadXML(dataString);
    except
    end;
  end;
end;