我有这个事件处理程序:
//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()
知道点击了哪个项目,但我似乎无法弄清楚如何将参数从test()
传递给loadajax()
。
我该怎么做?我尝试了几件事,但似乎总是打破剧本:(
感谢您的反馈!
答案 0 :(得分: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');
}
答案 1 :(得分: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