473,396 Members | 2,081 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

looping variables in a function literal

Below is a stripped down example of code I'm using to count links in a
list. My intent with the ShowLinkNumber() function was to display the
number of the current link. (e.g. click on link 2, and the message "2"
pops up; click on link 4, and you see a "4.")

For reasons I can't trace, my function always displays the last number
in the list. Why does it do this, and can anyone suggest a way to
achieve my goal without adding markup?

<html>
<head>
<script type="text/javascript">
<!--
function ShowLinkNumber()
{
var links = document.getElementsByTagName("li");

for ( var i=0; i < links.length; i++ )
{
if ( links[i].getElementsByTagName("a")[0] )
{
links[i].getElementsByTagName("a")[0].onclick = function()
{
alert(i);
};
}
}
}

window.onload = function()
{
ShowLinkNumber();
};
//-->
</script>
</head>
<body>
<ul>
<li>
<a href="#">do</a>
</li>
<li>
<a href="#">re</a>
</li>
<li>
<a href="#">mi</a>
</li>
<li>
<a href="#">fa</a>
</li>
<li>
<a href="#">sol</a>
</li>
</ul>
</body>
</html>

Oct 19 '05 #1
3 1280

2obvious wrote:
Below is a stripped down example of code I'm using to count links in a
list. My intent with the ShowLinkNumber() function was to display the
number of the current link. (e.g. click on link 2, and the message "2"
pops up; click on link 4, and you see a "4.")

For reasons I can't trace, my function always displays the last number
in the list. Why does it do this, and can anyone suggest a way to
achieve my goal without adding markup?

<html>
<head>
<script type="text/javascript">
<!--
function ShowLinkNumber()
{
var links = document.getElementsByTagName("li");

for ( var i=0; i < links.length; i++ )
{
if ( links[i].getElementsByTagName("a")[0] )
{
links[i].getElementsByTagName("a")[0].onclick = function()
{
alert(i);
};
}
}
}

window.onload = function()
{
ShowLinkNumber();
};
//-->
</script>
</head>
<body>
<ul>
<li>
<a href="#">do</a>
</li>
<li>
<a href="#">re</a>
</li>
<li>
<a href="#">mi</a>
</li>
<li>
<a href="#">fa</a>
</li>
<li>
<a href="#">sol</a>
</li>
</ul>
</body>
</html>
Your alert always shows the last number in the list because "i" is a
variable..well..that varies. Whatever the last value of "i" is the one
that will be assigned at the end.

To fix this behavior, replace the following:
if ( links[i].getElementsByTagName("a")[0] )
{
links[i].getElementsByTagName("a")[0].onclick = function()
{
alert(i);
};
}


if(links[i].getElementsByTagName("a")[0])
{
attachClick(links[i].getElementsByTagName("a")[0], i);
}

Then create a function:

function attachClick(anchor, number)
{
anchor.onclick = function () { alert(i); };
}

Oct 19 '05 #2
Ah, just what I needed! I was struggling to find a way to force the
onclick event assignment to execute. Thanks for the helping hand.

--E.

Oct 19 '05 #3

web.dev wrote:
2obvious wrote:
Below is a stripped down example of code I'm using to count links in a
list. My intent with the ShowLinkNumber() function was to display the
number of the current link. (e.g. click on link 2, and the message "2"
pops up; click on link 4, and you see a "4.")

For reasons I can't trace, my function always displays the last number
in the list. Why does it do this, and can anyone suggest a way to
achieve my goal without adding markup?

<html>
<head>
<script type="text/javascript">
<!--
function ShowLinkNumber()
{
var links = document.getElementsByTagName("li");

for ( var i=0; i < links.length; i++ )
{
if ( links[i].getElementsByTagName("a")[0] )
{
links[i].getElementsByTagName("a")[0].onclick = function()
{
alert(i);
};
}
}
}

window.onload = function()
{
ShowLinkNumber();
};
//-->
</script>
</head>
<body>
<ul>
<li>
<a href="#">do</a>
</li>
<li>
<a href="#">re</a>
</li>
<li>
<a href="#">mi</a>
</li>
<li>
<a href="#">fa</a>
</li>
<li>
<a href="#">sol</a>
</li>
</ul>
</body>
</html>
Your alert always shows the last number in the list because "i" is a
variable..well..that varies. Whatever the last value of "i" is the one
that will be assigned at the end.

To fix this behavior, replace the following:
if ( links[i].getElementsByTagName("a")[0] )
{
links[i].getElementsByTagName("a")[0].onclick = function()
{
alert(i);
};
}


if(links[i].getElementsByTagName("a")[0])
{
attachClick(links[i].getElementsByTagName("a")[0], i);
}

Then create a function:

function attachClick(anchor, number)
{
anchor.onclick = function () { alert(i); };

Oops, a typo. Should change that i to number. }


Oct 19 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
by: Rolf Kemper | last post by:
Dear Experts, I got stuck with the following problem and need your help. What I wnat to do is to get a set of distinct nodes. Before the distinct I have selected the multiple occourences...
4
by: David | last post by:
Hello. I am looking for advice on what is "best practice" regarding looping through a form to check its checkboxes and associated data fields. Here is what I am trying to do (Here is the page...
3
by: mr_burns | last post by:
hi, i was wondering if anybody could tell me when a function is called and variables are defined within that function, are the variables global where i can call and modify the variables in other...
4
by: louissan | last post by:
Hi all, I'm coming across a problem, and really do not get where it comes from. The goal: to loop over attributes read from "object" nodes in an imported XML file/flow (via XMLHTTP) and...
5
by: Bruce Lawrence | last post by:
I'm running Access 97 and my modules are looping if someone puts an invalid value in. The setup: 3 macros - get_clock_num, verify_clocknum, append_to_history 3 functions. each in their own...
3
by: Leiji Liu | last post by:
Hi, I am curious if there are any pre-defined varables (constants?) in C? I saw some code with __LINE__, __FILE__, etc. Are those located in some include files? LL
5
by: masood.iqbal | last post by:
My simplistic mind tells me that having local variables within looping constructs is a bad idea. The reason is that these variables are created during the beginning of an iteration and deleted at...
6
by: martin | last post by:
Hi, I am a web page and a web user control. My web user control is placed in my web page using the following directive <%@ Register TagPrefix="uc1" TagName="Header"...
114
by: Jonathan Wood | last post by:
I was just wondering what naming convention most of you use for class variables. Underscore, "m_" prefix, camel case, capitalized, etc? Has one style emerged as the most popular? Thanks for...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.