如何使这个代码与firefox浏览器兼容

时间:2012-09-18 05:31:53

标签: javascript

我对多浏览器兼容性有疑问。我想在下面的代码中使用event.target而不是event.srcElement来使它适用于firefox。

我使用了target = event.target || event.srcElement。它不起作用。任何帮助将不胜感激。

function jumptoPopupMenuItem(theMenuID) 
{                
  if (event.srcElement.className == "RightClickMenuItems") 
  {
    if (event.srcElement.getAttribute("url") != null)
    {        
      var strParameters = "";                                    
      if (theMenuID == "mnuAppointmentMenu")
      {
        strParameters = "AppointmentNumber=" + m_strAppointmentTypeYearNumber;
      }
      else if (theMenuID == "mnuAvailableHourMenu")
      {
        strParameters = "PreFillLanguageID=" + m_nLanguageID;
        strParameters = strParameters + "&PreFillInterpreterID=" + m_nInterpreterID;
        strParameters = strParameters + "&PreFillDateOfService=" + m_dtDateOfService;
      }
      if (event.srcElement.getAttribute("target") != null)
      {
        var PopupWindow = window.open(
            event.srcElement.url + strParameters, 
            event.srcElement.getAttribute("target"));
        PopupWindow.focus();
      }
      else
      {
        window.location = event.srcElement.url;
      }
    }
    hidePopupMenu(theMenuID);
  }
}

1 个答案:

答案 0 :(得分:0)

注册具有兼容性的事件处理程序的一些标准方法(非常简化的代码):

HTML:

<button onclick="eventHandlerFunc(event)" />
<!-- better to register as: -->
<button onclick="eventHandlerFunc.call(this,event)" />

JavaScript(addEventListener或attachEvent):

if (window.addEventListener) someElem.addEventListener("click",eventHandlerFunc,false);
else if (window.attachEvent) someElem.attachEvent("onclick",eventHandlerFunc);

JavaScript(元素属性):

someElem.onclick = eventHandlerFunc;

eventHandlerFunc()函数定义为:

function eventHandlerFunc(event) { // or var eventHandlerFunc = function(event) {
  event = event||window.event; // can be needed only for IE6-IE8
                               // because `event` parameter hide `event` global
                               // variable (`window.event`)
  var target = event.target||event.srcElement
}

注意:如果需要兼容this变量必须添加其他代码。

如果需要在其他函数中使用event变量(在eventHandlerFunc()中定义为参数),则必须将其发送到这些函数:

function eventHandlerFunc(event) {
  event = event||window.event; // can be needed only for IE6-IE8
  /*
  ...
  */
  jumptoPopupMenuItem(event,theMenuID);
}

function jumptoPopupMenuItem(event,theMenuID) {
}