jsfiddle.net上的JavaScript

时间:2011-03-28 08:25:13

标签: javascript

您将在此代码的最底部看到一个在窗口加载时运行的addEventHandler函数。如果我想在jsfiddle.net上测试这个,我怎么能/应该更改代码,考虑到页面没有在jsfiddle.net上加载。这是小提琴http://jsfiddle.net/mjmitche/KpTZq/

请记住我是新手,所以尽量详细地给出答案。感谢

function addEventHandler(oNode, evt, oFunc, bCaptures)
{
    if (window.attachEvent)
        oNode.attachEvent("on"+evt, oFunc);
    else
        oNode.addEventListener(evt, oFunc, bCaptures);
}
function getEventTarget(e) {
    if (window.event) return window.event.srcElement;
    else return e.target;
}

function div1Handler(evt) {
    var e = evt || window.event;
    var target = getEventTarget(e);
    var str = "Event handler for div1, target: " + target.getAttribute('id') + " , type: " + e.type;
    if (e.eventPhase) str+=" ; phase: " + e.eventPhase;
    alert(str);
    if (e.cancelBubble != null) e.cancelBubble=true;
    else e.stopPropagation();
}
function div2Handler(evt) {
    var e = evt || window.event;
    var target = getEventTarget(e);
    var str = "Event handler for div2, target: " + target.getAttribute('id') + " , type: " + e.type;
    if (e.eventPhase) str+=" ; phase: " + e.eventPhase;
    alert(str);
}
function div3Handler(evt) {
    var e = evt || window.event;
    var target = getEventTarget(e);
    var str = "Event handler for div3, target: " + target.getAttribute('id') + " , type: " + e.type;
    if (e.eventPhase) str+=" ; phase: " + e.eventPhase;
    alert(str);

}
function bodyHandler(evt) {
    var e = evt || window.event;
    var target = getEventTarget(e);
    var str = "Event handler for body, target: " + target.getAttribute('id') + " , type: " + e.type;
    if (e.eventPhase) str+=" ; phase: " + e.eventPhase;
    alert(str);
}

function initializeHandlers() {
    addEventHandler(document.getElementsByTagName("body")[0],"click",bodyHandler,false);
    addEventHandler(document.getElementById("div1"),"click",div1Handler,false);
    addEventHandler(document.getElementById("div2"),"click",div2Handler,false);
    addEventHandler(document.getElementById("div3"),"click",div3Handler,false);
    if (!window.event) {
        addEventHandler(document.getElementsByTagName("body")[0],"click",bodyHandler,true);
        addEventHandler(document.getElementById("div1"),"click",div1Handler,true);
        addEventHandler(document.getElementById("div2"),"click",div2Handler,true);
        addEventHandler(document.getElementById("div3"),"click",div3Handler,true);
    }
}

addEventHandler(window, "load", function(evt) { initializeHandlers() } );

3 个答案:

答案 0 :(得分:2)

试试这个:http://jsfiddle.net/KpTZq/2/

我所做的很简单。我改变了jsfiddle左侧的两个下拉列表,如下所示。 jsFiddle altered settings

之前您已在Mootools onLoad事件上编写了该事件。我的更改将代码放在页面的head标签上,没有任何换行。知道了吗?

答案 1 :(得分:1)

您应该在左栏中使用jsFiddle onDomReady事件。

答案 2 :(得分:0)

我猜您的问题是事件没有按预期绑定。原因是jsfiddle的标准配置是在onLoad上运行代码。所以你的事件永远不会被解雇,因为onLoad已经被解雇了。

要更改此设置,请使用no wrap(head)配置。要更改它,请使用左上角的下拉列表。