0

我有这个事件处理程序:

//Event Handler
var bindEvt = (function () {
    "use strict";
    if (document.addEventListener) {
        return function (element, event, handler) {
            element.addEventListener(event, handler, false);
        };
    }
    return function (element, event, handler) {
        element.attachEvent('on' + event, handler);
    };
}());

此代码循环遍历菜单元素并检测是否单击了一个。

// Ajax article loading
function test(){var menuitem = document.getElementsByTagName('nav')[0].childNodes;
    for(var i= 0; i < menuitem.length; i++){
        bindEvt(menuitem[i], "click", loadajax);
    }
};

function loadajax () {
    alert('yo')
}
bindEvt(window, "load", test);

现在我的问题是我想loadajax()知道点击了哪个项目,但我似乎无法弄清楚如何从 to 传递test()参数loadajax()

我该怎么做?我尝试了几件事,但似乎总是破坏脚本:(

感谢您的反馈意见!

4

2 回答 2

1

如果您只想知道单击了哪个对象,那么您可以this在事件处理程序中使用 的值。您不必将其传递给 loadajax。事件系统将设置this为导致事件的对象。也可以参考event.target

function loadajax (event) {
    event = event || window.event;   // deal with old IE

    // `this` points to the object that caused the event

    alert('yo');
}
于 2012-08-14T14:08:45.597 回答
0
function loadajax (X) {
console.log(X);
alert('yo')
}

X 应该是 Event 类型并且有很多很好的细节:

interface Event {

  // PhaseType
  const unsigned short      CAPTURING_PHASE                = 1;
  const unsigned short      AT_TARGET                      = 2;
  const unsigned short      BUBBLING_PHASE                 = 3;

  readonly attribute DOMString        type;
  readonly attribute EventTarget      target;
  readonly attribute EventTarget      currentTarget;
  readonly attribute unsigned short   eventPhase;
  readonly attribute boolean          bubbles;
  readonly attribute boolean          cancelable;
  readonly attribute DOMTimeStamp     timeStamp;
  void               stopPropagation();
  void               preventDefault();
  void               initEvent(in DOMString eventTypeArg, 
                               in boolean canBubbleArg, 
                               in boolean cancelableArg);
};

http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Event

于 2012-08-14T14:14:02.123 回答