473,554 Members | 2,921 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

DOM dynamically built table and addEventListene r....

This one is driving me nuts....

var tbl = document.create Element("table" );
var tbody = document.create Element("tbody" );

for(var i=0; i<10; i++) {
var row = document.create Element("tr");
var curVAR = someCurrentValu eOfArray[i];

row.addEventLis tener('click', function(e) {
alert(curVAR);
}, false);

var cell = document.create Element("td");
var cellText = document.create TextNode(i);
cell.appendChil d(cellText); row.appendChild (cell);

tbody.appendChi ld(row);
}
tbl.appendChild (tbody);
document.getEle mentById('tdiv' ).appendChild(t bl);

====

Now... Why isn't the curVAR 'assigned' to the row-alert-function???.
if I click one of the rows, only the last curVAR (10) is alerted, but the
i-variable is nicely showed 0 to 9 in the row....

Anyone???

Thanx in advance...
Jun 27 '08 #1
29 5418
"Quarco" <do**@bother.it writes:
This one is driving me nuts....

var tbl = document.create Element("table" );
var tbody = document.create Element("tbody" );

for(var i=0; i<10; i++) {
var row = document.create Element("tr");
var curVAR = someCurrentValu eOfArray[i];

row.addEventLis tener('click', function(e) {
alert(curVAR);
}, false);

var cell = document.create Element("td");
var cellText = document.create TextNode(i);
cell.appendChil d(cellText); row.appendChild (cell);

tbody.appendChi ld(row);
}
tbl.appendChild (tbody);
document.getEle mentById('tdiv' ).appendChild(t bl);

====

Now... Why isn't the curVAR 'assigned' to the row-alert-function???.
if I click one of the rows, only the last curVAR (10) is alerted, but the
i-variable is nicely showed 0 to 9 in the row....

Anyone???
The i and curVar variables are re-assigned in the loop (javascript
does not have block scope, only function scope), so all your event
handlers are closing over the same curVar variable, which will have
someCurrentEtc[9] as its value at the end of the loop.

You need to create a new variable to close over, by creating a new
scope:

(function(curVa r) { // or make a named function and call that
row.addEventLis tener('click', function(e) {
alert(curVAR);
}, false);
})(curVar);
--
Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/
Jun 27 '08 #2
Quarco wrote:
>
Now... Why isn't the curVAR 'assigned' to the row-alert-function???.
if I click one of the rows, only the last curVAR (10) is alerted, but the
i-variable is nicely showed 0 to 9 in the row....
You could save curVar as a property of the element ( td / tr ) :

<html><head><sc ript>
window.onload= function () {
var d= document,
anArray= ['a0','b1','c2', 'd3','e4','f5', 'g6','h7','i8', 'j9'],
y= function (p) { return d.createElement (p) },
tbody= y("tbody"),
i, cell;

for(i= 0; i< 10; i++) {
(tbody.appendCh ild(y('tr'))).a ppendChild(cell = y("td"));
cell.innerHTML= i;
cell.curVAR= anArray[i];
cell.addEventLi stener('click', function(e) { alert(this.curV AR) },
false);
}

(d.getElementBy Id('tdiv').appe ndChild(y("tabl e"))).appendChi ld(tbody);
};
</script></head><body><div id="tdiv"></div></body></html>

--Jorge.
Jun 27 '08 #3
Jorge wrote:
Quarco wrote:
>Now... Why isn't the curVAR 'assigned' to the row-alert-function???.
if I click one of the rows, only the last curVAR (10) is alerted, but the
i-variable is nicely showed 0 to 9 in the row....

You could save curVar as a property of the element ( td / tr ) :
Recommended against because that would mean augmenting a host object which
is error-prone. Search the archives.
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
Jun 27 '08 #4
Taking a bow...
Thank you Joost...!!!
:-)
"Joost Diepenmaat" <jo***@zeekat.n lschreef in bericht
news:87******** ****@zeekat.nl. ..
"Quarco" <do**@bother.it writes:
>This one is driving me nuts....

var tbl = document.create Element("table" );
var tbody = document.create Element("tbody" );

for(var i=0; i<10; i++) {
var row = document.create Element("tr");
var curVAR = someCurrentValu eOfArray[i];

row.addEventLis tener('click', function(e) {
alert(curVAR);
}, false);

var cell = document.create Element("td");
var cellText = document.create TextNode(i);
cell.appendChil d(cellText); row.appendChild (cell);

tbody.appendChi ld(row);
}
tbl.appendChild (tbody);
document.getEle mentById('tdiv' ).appendChild(t bl);

====

Now... Why isn't the curVAR 'assigned' to the row-alert-function???.
if I click one of the rows, only the last curVAR (10) is alerted, but the
i-variable is nicely showed 0 to 9 in the row....

Anyone???

The i and curVar variables are re-assigned in the loop (javascript
does not have block scope, only function scope), so all your event
handlers are closing over the same curVar variable, which will have
someCurrentEtc[9] as its value at the end of the loop.

You need to create a new variable to close over, by creating a new
scope:

(function(curVa r) { // or make a named function and call that
row.addEventLis tener('click', function(e) {
alert(curVAR);
}, false);
})(curVar);
--
Joost Diepenmaat | blog: http://joost.zeekat.nl/ | work: http://zeekat.nl/

Jun 27 '08 #5
On Jun 2, 8:21*pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
wrote:
Recommended against because that would mean augmenting a host object which
is error-prone. *Search the archives.
I didn't know, and I do it all the time !
Would you please tell me why, in a few words ?
Is it a problem, specifically, of a certain browser ?
(I'll look into the archives as well, I promise)

Thanks,
--Jorge.
Jun 27 '08 #6
On Jun 2, 8:21*pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
wrote:
You could save curVar as a property of the element ( td / tr ) :

Recommended against because that would mean augmenting a host object which
is error-prone. *Search the archives.
I didn't know, and I do it all the time !
Would you tell me why is it bad, in a few words ?
(I'll look into the archive as well, I promise)

Thanks,
--Jorge.
Jun 27 '08 #7
Jorge wrote:
Thomas 'PointedEars' Lahn wrote:
>Recommended against because that would mean augmenting a host object which
is error-prone. Search the archives.

I didn't know, and I do it all the time !
Tough luck.
Would you please tell me why, in a few words ?
In contrast to native objects, host objects do not need to support
augmentation. See the ECMAScript Language Specification, Edition 3 Final,
subsection "8.6.2 Internal Properties and Methods".
Is it a problem,
Yes.
specifically, of a certain browser ?
No, it can cause your Web application to break. Silently, or with an error
message. Anywhere, anytime.
(I'll look into the archives as well, I promise)
Good.
HTH

PointedEars
--
Anyone who slaps a 'this page is best viewed with Browser X' label on
a Web page appears to be yearning for the bad old days, before the Web,
when you had very little chance of reading a document written on another
computer, another word processor, or another network. -- Tim Berners-Lee
Jun 27 '08 #8
On Jun 2, 9:53*pm, Thomas 'PointedEars' Lahn <PointedE...@we b.de>
wrote:
Jorge wrote:
Thomas 'PointedEars' Lahn wrote:
Recommended against because that would mean augmenting a host object which
is error-prone. *Search the archives.
I didn't know, and I do it all the time !

Tough luck.
Would you please tell me why, in a few words ?

In contrast to native objects, host objects do not need to support
augmentation. *See the ECMAScript Language Specification, Edition 3 Final,
subsection "8.6.2 Internal Properties and Methods".
Is it a problem,

Yes.
specifically, of a certain browser ?

No, it can cause your Web application to break. *Silently, or with an error
message. *Anywhere, anytime.
But, for example :

var y= function (p) { return document.create Element(p) },
e= y('tag');

e.property= "whatever";

Is e a "host object" ?

Or you mean :

(y('tag')).prop erty= "whatever";

??

--Jorge.
Jun 27 '08 #9
Jorge wrote:
Thomas 'PointedEars' Lahn wrote:
>[Trying to augment host objects] can cause your Web application to
break. Silently, or with an error message. Anywhere, anytime.

But, for example :

var y= function (p) { return document.create Element(p) },
This as it is does not make much sense. See our recent discussion about the
viability of Prototype.js's $() method.
e= y('tag');

e.property= "whatever";

Is e a "host object" ?
`e' is *a reference to* a host object then (probably an object that
implements an element-related interface of W3C DOM Level 2 HTML).

In ECMAScript implementations , you can only work with references to objects,
never with objects directly.
Or you mean :

(y('tag')).prop erty= "whatever";

??
You could also write

y('tag').proper ty = "whatever";

or

[{foo: y('tag')}][0]["foo"].property = "whatever";

and so on with the same (here: possibly disastrous) outcome. How you
construct the reference to an object makes no difference regarding the
kind of object you are referring to.

However, your second variant adds further error-proneness as y() may not
return an object reference or a primitive value convertible to an object in
which case the property lookup would then result in a TypeError (exception).

With the first variant you can at least do feature-testing on the return
value and perhaps also on the property before you attempt to assign to the
property of the object; that would generally seem to be a wise course of
action, with the exception of universally supported properties of native
objects.
Please trim your quotes.
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f8************ *******@news.de mon.co.uk>
Jun 27 '08 #10

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

Similar topics

1
4306
by: ajay | last post by:
I have following code for a slide menu but i twiked it to work for a single level menu. Open it in a Browser to get a clear picture. I have 2 Qs 1) How to make first entry as non-link. i.e i want to make first text as Table Heading/menu category. For examle in the given menu i want to make a heading as "Comp. Languages" which won't be a...
6
3300
by: Thomas | last post by:
Hi, I'm having a problem with the dynamically created inputfields in Internet Explorer. The situation is the following: - I have a dynamically created table with a textbox in each Cell. - It is possible to Add and Delete rows - Some cells have special attributes (readonly and events) Here's a snippet of the code:
16
1811
by: sirsean | last post by:
Hi all. I'm trying to dynamically build menus and objects after my page loads. Data is stored in an XML file and is parsed at runtime into Javascript objects. At the moment, I'm working on creating menu items from these objects. The parsing works fine (using Sarissa), and Firefox builds the menu no problem. IE, however, does not. The...
20
12870
by: David | last post by:
I have a one-line script to add an onunload event handler to the body of the document. The script is as follows: document.getElementsByTagName("BODY").onunload=function s() {alert("s")} Now obviously, I put the alert("s") part in for debugging purposes, just to make sure the error wasn't in any code I was going to be running. This line...
2
3375
by: jmarendo | last post by:
Hello, After reading through the "Table Basics - DOM - Refer to table cells" example at mredkj.com , I modified the code for my own purposes. In the modified version, I create a hyperlink and place it in the last cell of each row that I create dynamically using DOM methods. Everything is working well (that is, just like the original...
7
2518
by: Ron Goral | last post by:
Hello I am new to creating objects in javascript, so please no flames about my coding style. =) I am trying to create an object that will represent a "div" element as a menu. I have written several methods that are working fine. The problem is if I want to dynamically assign an event handler to the object, the event handler is not called....
21
29747
by: Leena P | last post by:
i want to basically take some information for the product and let the user enter the the material required to make this product 1.first page test.php which takes product code and displays prodcut anme have used ajax to avoid refreshing of page this works fine 2.now i have created one row with checkbox|select box|text|text|text|text|...
0
7600
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, 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...
0
7521
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...
0
8042
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7563
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...
0
7889
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6145
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
3560
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...
0
3548
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2020
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.