Hello.
I have a javascript object with one attribute (name) and one method
(showName). Each object instance appends a DIV to the document's body. I
want that when the user clicks over the DIVS the alert shows the name of
the instance which has created the DIV.tancia que ha creado ese DIV:
See online:
When the user clicks on the first square the message box should show:
Object1. When the user clicks on the second square the message box
should show: Object2.
I don't know how to do that. The following sentence doesn't work.
this.div.onclic k=this.muestraN ombre;
Thanks. And excuse my poor english.
<html>
<head>
<script type="text/javascript">
function Objeto(nombre) {
this.nombre=nom bre;
this.div=docume nt.createElemen t('div');
this.div.style. border='1px solid #000';
this.div.style. width='10px';
this.div.style. height='10px';
this.div.onclic k=this.muestraN ombre;
// Esto no funciona, la función se ejecuta pero
// la referencia this se pierde y aparece 'undefined'
var body=document.g etElementsByTag Name('body').it em(0);
body.appendChil d(this.div);
}
function MuestraNombre() {
alert(this.nomb re);
}
Objeto.prototyp e.muestraNombre =MuestraNombre;
</script>
</head>
<body>
<script type="text/javascript">obj 1=new Objeto('Objeto1 ');</script>
<p></p>
<script type="text/javascript">obj 2=new Objeto('Objeto2 ');</script>
</body>
</html>
I have a javascript object with one attribute (name) and one method
(showName). Each object instance appends a DIV to the document's body. I
want that when the user clicks over the DIVS the alert shows the name of
the instance which has created the DIV.tancia que ha creado ese DIV:
See online:
When the user clicks on the first square the message box should show:
Object1. When the user clicks on the second square the message box
should show: Object2.
I don't know how to do that. The following sentence doesn't work.
this.div.onclic k=this.muestraN ombre;
Thanks. And excuse my poor english.
<html>
<head>
<script type="text/javascript">
function Objeto(nombre) {
this.nombre=nom bre;
this.div=docume nt.createElemen t('div');
this.div.style. border='1px solid #000';
this.div.style. width='10px';
this.div.style. height='10px';
this.div.onclic k=this.muestraN ombre;
// Esto no funciona, la función se ejecuta pero
// la referencia this se pierde y aparece 'undefined'
var body=document.g etElementsByTag Name('body').it em(0);
body.appendChil d(this.div);
}
function MuestraNombre() {
alert(this.nomb re);
}
Objeto.prototyp e.muestraNombre =MuestraNombre;
</script>
</head>
<body>
<script type="text/javascript">obj 1=new Objeto('Objeto1 ');</script>
<p></p>
<script type="text/javascript">obj 2=new Objeto('Objeto2 ');</script>
</body>
</html>
Comment