开发者

YUI Listener set on startup lost

I'm trying to monitor the clicks on a web page that is written in YUI2. The events seem to be getting wiped away and the callback function isn't getting called.

The links that I am trying to monitor are all of class 'action-link', but none have an id set on the page. I tried calling YAHOO.util.Event.addListener() first with the actual element, but that didn't work. Next I tried adding an id to each of the element and then calling it, but that still didn't work.

But using the JS debugger, I see that the element id's have been added to all of the links. But the Listeners are not set. In the debugger, I can call YAHOO.util.Event.getListeners() on the various links and see that they are all null. Yet, in the debugger I can 开发者_如何学编程manually call YAHOO.util.Event.addListener(elementIDString, "click", fnCallback) and then clicking on the link causes the callback to be entered.

function fnCallback(e) {
  alert("click event: " + e.currentTarget.title);
}

function afterLoad()
{
    var elements = YAHOO.util.Dom.getElementsByClassName('action-link');
    for ( var element in elements )
    {
    if(elements[element].id=="") elements[element].id = "el_" + element;
        YAHOO.util.Event.addListener(elements1[element].id, "click", fnCallback);
    }

}
YAHOO.util.Event.onContentReady( "Share", afterLoad, null, false ); 


YAHOO.util.Event.addListener preferably takes a DOM element as its first argument like this:

function afterLoad()
{
    var elements = YAHOO.util.Dom.getElementsByClassName('action-link');
    for (var i = 0; i < elements.length; i++)
    {
        YAHOO.util.Event.addListener(elements[i], "click", fnCallback);
    }

}
YAHOO.util.Event.onDOMReady(afterLoad); 

It can also be passed an id string, but that is not required in this case since you already have a list of DOM elements.

In addition, you should not iterate an array with for x in yy as that can easily include non-numeric indexes such as custom properties.

Or you can write it this way using an anonymous function:

YAHOO.util.Event.onDOMReady(function() {
    var elements = YAHOO.util.Dom.getElementsByClassName('action-link');
    for (var i = 0; i < elements.length; i++) {
        YAHOO.util.Event.addListener(elements[i], "click", fnCallback);
    }
}); 

FYI, YAHOO.util.Event.onContentReady("Share", afterLoad) will only work if "Share" is the id of an item in the page AND, the items you want to operate on in afterLoad are before that item in the page or children of that item in the page. Since I was unsure if this might also be a part of the problem, I switched to onDOMReady() which is simpler.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜