function buttonClick(buttonId,str) {
this.button = document.getElementById(buttonId);
this.message = str;
this.button.onclick = this.clicked;
this.clicked = function() {
this.showMsg();
};
this.showMsg = function() {
alert(this.message);
};
}
new buttonClick("myButton1","你点击了按钮1");
new buttonClick("myButton2","你点击了按钮2");
为什么在触发click事件时运行到this.showMsg();这句就说对象不支持此属性或方法呢?求救。不理解啊,,this不是只buttonClick这个类了?那如果还要调用本类中的其他方法怎么能做到?
解决方案 »
- html中如何把js代码的某个变量值显示出来
- 关于JScript.Encode
- 如何在HTML获取参数以及根据参数更改LABLE或者文本值
- 如何用JScript实现 <A HREF="1.htm" target=leftFrame>1</A>
- JS 正则表达式问题
- 关于JS文件的加载顺序,高手请进
- ====大家讨论:错误在哪?考考你,在线====
- 没分了,求匹配html的正则表达式!
- help,有关lotus notes的问题
- jquery 列表数据上下移动
- jquery append新元素如何使用类似trigger方法
- jquery1.2.6和1.4.4的jQuery(expression, [context])的区别?
this.button = document.getElementById(buttonId);
this.message = str;
this.button.onclick = this.clicked;
this.clicked = function() {
alert(this.message);
};
}原因是JS点击运行的先后顺序问题 在执行showMsg()的时候 改方法未找到
不是啊,我换了顺序还是不行,2楼这样固然可以,因为要处理的只有一条alert语句。但是,如果this.clicked需要处理很多东西,还要用到buttonClick类中的其他函数,怎么写?
<input type="button" id="myButton2" value="button2">
<script>
function buttonClick(buttonId,str) {
this.button = document.getElementById(buttonId);
this.message = str;
var that=this;
this.button.onclick = function() {
that.showMsg();
};
this.showMsg = function() {
alert(this.message);
};
}
new buttonClick("myButton1","你点击了按钮1");
new buttonClick("myButton2","你点击了按钮2");
</script>
这样就可以了!用that去保存this!
this的混用导致了没有效果或者错误!
...........
}
方法a放在html的head部function buttonClick(buttonId,str) {
var button = document.getElementById(buttonId);
button.onclick= a(str);
}
谢谢,OK啦!一直弄不懂js中this的问题。好好学习啦!js的面向对象很复杂啊也谢谢cjg520jie,但我只是把我遇到的问题抽象出来啦。问题就是js类中this的问题。