Dec 4, 2009 1:42 pm
Generale ClusterHello,
I have an unordered list with sublists in it and I've used it to make an
expandable tree menu.
This is my sample page: http://tinyurl.com/y88ouj8
When I click on "prodotti", I get that "Clienti" submenu expands. I
would expect the "prodotti" menu to expand when clicking it.
My problem is that when I call addEventListener in firefox, it seems to
attach the listener always to the same element.
What is the problem in the code?
Thank you
Regards
elimina unsampdoriano per rispondere via email
Dec 7, 2009 10:57 am
Matthias ReuterGenerale Cluster wrote:
> My problem is that when I call addEventListener in firefox, it seems to
> attach the listener always to the same element.
> What is the problem in the code?
> attach the listener always to the same element.
> What is the problem in the code?
That is the code:
function hideByClassName(clName) {
list = document.getElementsByTagName("ul");
for (i=0;i<list.length;i++) {
if (list[i].className==clName) {
var oText = document.createTextNode("+");
list[i].style.display="none";
var mynode=list[i];
list[i].parentNode.insertBefore(oText,list[i].parentNode.childNodes[0]);
try {
list[i].parentNode.childNodes[1].addEventListener("click",
function(evt){toggle(mynode,evt)}, true);
} catch (err) {
list[i].parentNode.attachEvent("onclick",
function(evt){toggle(mynode,evt)});
}
}
}
}
The problem lies here:
function(evt){toggle(mynode,evt)}
mynode is a reference. You expect it to point to the element it referenced
when you added the event listener, but is is evaluated when the handler is
called. Therefore mynode points to the last item of list.
A solution is to extract the target in toggle:
function toggle (e) {
var event = e || window.event;
var target = e.target || e.srcElement;
// ...
}
Matt
Dec 7, 2009 9:10 pm
Generale ClusterMatthias Reuter ha scritto:
> Generale Cluster wrote:
>
[CUT]>
>> My problem is that when I call addEventListener in firefox, it seems
>> to attach the listener always to the same element.
>> to attach the listener always to the same element.
> The problem lies here:
>
> function(evt){toggle(mynode,evt)}
>
> mynode is a reference. You expect it to point to the element it
> referenced when you added the event listener, but is is evaluated when
> the handler is called. Therefore mynode points to the last item of list.
[CUT]>
> function(evt){toggle(mynode,evt)}
>
> mynode is a reference. You expect it to point to the element it
> referenced when you added the event listener, but is is evaluated when
> the handler is called. Therefore mynode points to the last item of list.
> Matt
thank you
regards
elimina unsampdoriano per rispondere via email
Previous Thread: Baffling Results from my Javascript Class(-ishness) (Ninjas explain!)
Next Thread: File input problem