Назначить на обработчик события метод обьекта
В конструкторе, при создании обьекта определенному диву надо назначить обработчик события onclick. По onclick должен вызываться метод созданного объекта. Как это сделать? У меня метод хотя и вызывается, но не у созданного объекта, а сам по себе, а свойства объекта равны undefined
|
http://javascript.ru/tutorial/object/thiskeyword
Лучше всего в своих функциях установки событий добавить возможность передавать scope, в котором будут вызываться обработчики. |
Заверни обработчик в функцию, и в ней вызывай его в нужном контексте.
|
Цитата:
Вот простенький пример, иллюстрирующий проблему <!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=utf-8" /> <title>Пример</title> <style type="text/css"> #button {background:#f00; color:#fff; font-weight:bold; padding:3px 5px; cursor:pointer; float:left} </style> <script type="text/javascript"> window.onload= function() { obj= new myclass(document.getElementById('button')) } function myclass(objref) { this.message="Я обект, тарм-пам пам" this.obj=objref myclass.prototype.helloworld = function() { alert(this.message) //Должен при клике на кнопку сказать 'Я обект, тарм-пам пам', а сообщает undefined } this.obj.onclick=this.helloworld; //this.obj.onclick=this.helloworld.call(this); //this.obj.onclick=function() {this.helloworld()}; //this.obj.onclick=myclass.prototype.helloworld.call(this); //- это все тоже не работает } </script> </head> <body> <div id="button">нажмии меня</div> </body> </html> |
function myclass(objref) { var that = this; this.message="Я обект, тарм-пам пам" this.obj=objref this.helloworld = function() { alert(that.message) //Должен при клике на кнопку сказать 'Я обект, тарм-пам пам', а сообщает undefined } this.obj.onclick=this.helloworld; //this.obj.onclick=this.helloworld.call(this); //this.obj.onclick=function() {this.helloworld()}; //this.obj.onclick=myclass.prototype.helloworld.call(this); //- это все тоже не работает } И весь раздел до кучи http://javascript.ru/tutorial/object |
<!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=utf-8" /> <title>Пример</title> <style type="text/css"> #button {background:#f00; color:#fff; font-weight:bold; padding:3px 5px; cursor:pointer; float:left} </style> <script type="text/javascript"> window.onload = function() { new myclass(document.getElementById('button')); }; function myclass(objref) { this.message = "Я обект, тарм-пам пам"; this.obj = objref; var self = this; this.obj.onclick = function() { self.helloworld(); }; } myclass.prototype.helloworld = function() { alert(this.message) //Должен при клике на кнопку сказать 'Я обект, тарм-пам пам', а сообщает undefined }; </script> </head> <body> <div id="button">нажмии меня</div> </body> </html> |
Спасибо, работает. Но дальше новая проблема. В методе объекта вызываю setInterval, в качестве функции к которой метод того же объекта. Но почему-то, независимо от того в каком объекте ставится setInterval, в качестве функции в нее попадает метод последнего объекта. Вот пример
<!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=utf-8" /> <title>Пример</title> <style type="text/css"> #button, #button2 {background:#f00; color:#fff; font-weight:bold; padding:3px 5px; cursor:pointer; float:left; position:relative} #button2 {background:#f80;} </style> <script type="text/javascript"> window.onload= function() { obj= new myclass(document.getElementById('button')) obj2= new myclass(document.getElementById('button2')) } function myclass(objref, message) { this.message=message this.obj=objref var self = this; this.offset=0 this.timer = 0 this.intervalref myclass.prototype.animate = function() { if(this.timer==0) { this.intervalref=setInterval(function() {self.animate()}, 5) //при клике кнопка должна плавно съехать вниз на30 px. Правая так и делает, но при this.timer= 30 / 3 //нажатии на левую self.animate() вызывает obj2.animate() вместо своей obj.animate() } else { this.offset+= 3; this.obj.style.top=this.offset+'px' this.timer-- } if(this.timer==0) { clearInterval(this.intervalref) } } this.obj.onclick = function() {self.animate()}; } </script> </head> <body> <div id="button">нажмии меня</div> <div id="button2">нажмии меня 2</div> </body> </html> |
Цитата:
|
Фух, наконец то получилось. Сразу не заметил ваше сообщение. В общем получилось решить задачу, скрестив ваш метод и Riim. А слова prototype я все из своего скрипта повырезал.
Рабочий пример <!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=utf-8" /> <title>Пример</title> <style type="text/css"> #button, #button2 {background:#f00; color:#fff; font-weight:bold; padding:3px 5px; cursor:pointer; float:left; position:relative} #button2 {background:#f80;} </style> <script type="text/javascript"> window.onload= function() { obj= new myclass(document.getElementById('button')) obj2= new myclass(document.getElementById('button2')) } function myclass(objref, message) { this.message=message this.obj=objref var self = this; this.changecontent = function () { this.obj.innerHTML=this.obj.innerHTML+' :)' this.animate() } this.animate = function() { if(this.timer==0) { this.intervalref=setInterval(function() {self.animate()}, 5) this.timer= 30 / 3 } else { this.offset+= 3; this.obj.style.top=this.offset+'px' this.timer-- } if(this.timer==0) { clearInterval(this.intervalref) } } this.offset=0 this.timer = 0 this.intervalref this.obj.onclick = function() {self.changecontent()}; } </script> </head> <body> <div id="button">нажмии меня</div> <div id="button2">нажмии меня 2</div> </body> </html> |
я бы действительно скрестил: вынес все методы в прототип (а что сейчас от варианта Riim я хз)
|
Часовой пояс GMT +3, время: 15:39. |