Hi Guys,
Im trying to create lots of divs all with there own onclick event...
Heres the code: -
<html>
-
<head>
-
<script language="javascript">
-
-
function initialise(){
-
data = {"item 1" : "a","item 2" : "b", "item 3" : "c"};
-
-
for (key in data)
-
{
-
itemDiv = document.createElement("DIV");
-
itemDiv.innerHTML = key;
-
itemDiv.id = key;
-
-
var otherDiv = itemDiv;
-
itemDiv.onclick = function(){alert(otherDiv.id);}
-
document.body.appendChild(itemDiv);
-
}
-
-
}
-
</script>
-
-
</head>
-
<body onload="initialise();">
-
body text.
-
</body>
-
</html>
Seems like no matter what way i do it the onclick events all end up being the same as whichever one was created last.
I put the var otherDiv = itemDiv; line in to try and change this, but its still the same.
Can anyone help??
Cheers
Andy
6 1750 gits 5,390
Recognized Expert Moderator Expert
use the following 'explicit' closure construct: - itemDiv.onclick = function(param) {
-
return function() { alert(param); };
-
}(otherDiv.id);
kind regards
sorry i dont really understand how this works.
can you sub it into my posted code so the example works.
Thanks
Andy
gits 5,390
Recognized Expert Moderator Expert
just put it where you assign your onclick event ... it just replaces that ...
kind regards
[HTML]<html>
<head>
<script language="javas cript">
function initialise(){
data = {"item 1" : "a","item 2" : "b", "item 3" : "c"};
for (key in data)
{
itemDiv = document.create Element("DIV");
itemDiv.innerHT ML = key;
itemDiv.id = key;
itemDiv.onclick = function(){aler t(this.id);}
document.body.a ppendChild(item Div);
}
}
</script>
</head>
<body onload="initial ise();">
body text.
</body></html>[/HTML]
Two logical reasons it doesn't work:
1. there is no use to state var otherDIv = itemDiv. This would just create another div element with empty content
2. most important is that, in each for loop steps, you used the same var (itemDiv), in first loop itemDiv = item 1, second loop itemDiv = item 2, last loop you set itemDiv = item 3. When all javascript finished, it use item 3 as variable and alert item3.id, that is why you always got item 3 as result. Instead, you can use this.id to refer to its own id when you click on an item.
Is this clear enough?
Ah yes,
That does make it a bit clearer thanks.
I didnt understand that it was alerting the same variable for each one, i thought it would treat each one as a new instance.
Cheers
Andy
gits 5,390
Recognized Expert Moderator Expert
Two logical reasons it doesn't work:
1. there is no use to state var otherDIv = itemDiv. This would just create another div element with empty content
2. most important is that, in each for loop steps, you used the same var (itemDiv), in first loop itemDiv = item 1, second loop itemDiv = item 2, last loop you set itemDiv = item 3. When all javascript finished, it use item 3 as variable and alert item3.id, that is why you always got item 3 as result. Instead, you can use this.id to refer to its own id when you click on an item.
Is this clear enough?
in for-loops you have to use closures for such assignments ... that is exactly what i showed you with the given example. as you can see it passes a reference to the function that is immediatly executed and the returned function stores that passed reference and alerts the correct id ...
the 'this-construct' should work too ... but sometimes you just need the loop-index or something that is not in the this-context of the current node in your handler function and then you need the closure ...
kind regards
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Ashish Shridharan |
last post by:
Hi All
I have been trying to add a control to the header cell of
a datagrid on my ASP.NET page. These controls are defined
in the HTML as ASP.NET web controls.
They are being added into the header of the datagrid in
the "ItemDataBound" method of the grid. However, once,
they are added in the grid, i seem to lose the event
handler for the same control. Is there anyone who has
tried this before and knows why this is hapenning ??
|
by: Macamba |
last post by:
Hi all,
I am currently developing a website for a voluntary organisation. It is
my first step in website development. The dynamic menu I developed has
some bugs, which I addressed in another post. In this post I want to ask
you why my code behaves differently in IE, while it behaves like I
expect in Mozilla and Opera. What I would like to see addressed is what
I need to do to get the same behaviour in all 3 browsers. I know each
browser...
|
by: pizzy |
last post by:
INTRO: I tried to clean it up for easy reading. I hope I didn't make
any mistakes.
PROBLEM: WOW, this is some crazy sh!t. I can't get my checkbox (see
"TAGSELECTED") to print my textboxes (see "TAG#") when more than 1
number (see "VLANS") is inputed into my form.
QUESTION: How do I make my dynamic form have a dynamic input box(which
is created by checking the checkbox and calling the functionC1) inside
it and still be able to pass the...
|
by: Aaron Gervais |
last post by:
I am brand-new to javascript, but after reading some tutorials online I
was able to make a dynamic HTML photo gallery in javascript. It works
fine in all browsers except IE6 (big surprise). I've been looking
around online for solutions, but the fixes I have seen don't seem to
work. I assume I am misunderstanding something... I was using
element.setAttribute but have changed my code to avoid that. Here is an
example. IE6 displays the link...
|
by: kusanagihk |
last post by:
To all,
I'm working on a javascript to dynamic build a common set of HTML
controls.
01) I've used the DOM object to build a <div> tag; then build 1 <input
type='button'/> and 1 <input type='text'> object
02) by using appendChild () method, I've successfully append the button
and the textbox under the div tag (or container in this case)
03) but now I would like to add the javascript onclick event on the
button I've just created...
| |
by: comicgeekspeak |
last post by:
Hi there,
I am trying to write a loop that will add 10 divs to the screen. Each
div will have an onclick event. The function that will be called
onclick requires a parameter. That parameter is dynamic based on the
index of the loop. In Firefox this is no problem. However in IE I get
some results that I wouldn't expect.
Here is my code:
|
by: polymorphic |
last post by:
I have succeeded in embedding PDF files in a dynamic iframe. The problem is that I need the PDF to cache. If the PDF remains the same from page load to page load then the pdf is somehow cached with the html page. But if I try to navigate to another pdf in the IFRAME then no caching occurs. Is the problem in the IFRAME reloading instead of just refreshing the pdf?
<SCRIPT type="text/javascript">
var pageNo;
var nav;
var iframe;
var...
|
by: bmallett |
last post by:
First off, i would like to thank everyone for any and all help with this. That being said, I am having a problem retrieving/posting my dynamic form data. I have a form that has multiple options within options. I have everything being dynamically named from the previously dynamically named element. (I hope this makes sense.) I am not able to retrieve any of the dynamically created values. I can view them on the source page but can't pull them...
|
by: azegurb |
last post by:
hi
I have just took from internet dinamic table. this table is dynamic and its rows dynamically can be increased.
but i would like how create SUM function that automatically sums each added row value (text value)
here is the code
if possible please help me
Thanks beforehand
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |