JS onclick triggers wrong object
Posted
by Clemens Prerovsky
on Stack Overflow
See other posts from Stack Overflow
or by Clemens Prerovsky
Published on 2010-03-26T23:02:27Z
Indexed on
2010/03/27
0:13 UTC
Read the original article
Hit count: 658
Hi guys,
what I'm trying to do here is to associate a DOM object with an instance of a JS object, which will provide some meaningfol methods later on ;) At this point I just want to handle my JS object the click event, whilst keeping it's references intact.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
<script type="text/javascript">
// my object, which will hold a reference to a single DOM object
obj = function(domobj) {
this.o = domobj;
my = this;
var ref = my.click;
this.o.onclick = ref;
}
// my objects click function
obj.prototype.click = function() {
alert(my.o.innerHTML);
}
// create objects with references
$(document).ready(function() {
o1 = new obj(document.getElementById('b1'));
o2 = new obj(document.getElementById('b2'));
});
</script>
</head>
<body>
<button id="b1">button 1</button>
<button id="b2">button 2</button>
</body>
</html>
Expected result: when clicking on button 1, the text "button 1" should be alerted.
Current result: when clicking button 1, the text "button 2" is alerted.
What I found out so far is that the wrong instance of obj is triggered from the click event, even though o1 and o2 maintain correct references to their corresponding DOM object.
Any ideas how to solve this?
Thanks for your help!
Best regards, Clemens
© Stack Overflow or respective owner