John Smith wrote:
[snip]
<script defer="false" type="text/javascript">
Last time I looked, defer was a boolean attribute. A boolean attribute
does not have "true" and "false" values: its presence means "true" and
its absence "false". You seem to want the latter so don't include the
attribute at all.
The defer attribute can only have one value - defer. That is,
<script type="text/javascript" defer="defer">
In HTML, the value can be omitted entirely.
function initNavlists(){
var nav = document.getElementById('navlist');
if (nav){
var links = nav.getElementsByTagName('a');
for (var i=0;i<links.length;i++)
{
var str = links[i].innerHTML;
//alert(str);
links[i].onclick = function(){ alert(str); };
}
}
}
Don't forget to feature-detect[1] those DOM methods before using them.
[snip]
Why i always get the last item in the alert box?
The function expression you assign to the onclick property forms a
closure preventing the str variable, among other things, from being
garbage collected. Even though the function objects will be unique,
they will all have the same scope chain sharing the same variables. In
other words, str will be the same for all of them, and by the end of
the loop, str will contain the innerHTML value of the last link.
Though you could take a more complex route to solve this, it would
just be a waste of memory and time. The simplest thing to do is to
refer to the innerHTML property directly:
function initNavLists() {
function listener() {
alert(this.innerHTML);
}
/* ... */
for(var i = 0, n = links.length; i < n; ++i) {
links[i].onclick = listener;
}
}
Notice that the this operator will refer to element on which the
listener function was fired.
Hope that helps,
Mike
[1] <URL:http://www.jibbering.com/faq/faq_notes/not_browser_detect.html>
--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.