<script>
function Debug(num){
this.num = num;
this.out = function(){
alert(this.num);
}
}
var dbg = new Debug(555);
</script>
<body>
<div id="Layer1">clickme</div><script>document.getElementById('Layer1').onclick = function(){dbg.out();}</script>
</body>
function Debug(num){
this.num = num;
this.out = function(){
alert(this.num);
}
}
var dbg = new Debug(555);
</script>
<body>
<div id="Layer1">clickme</div><script>document.getElementById('Layer1').onclick = function(){dbg.out();}</script>
</body>
解决方案 »
- javascript
- 点击onclick事件触发调用其他JS文件
- extjs template 怎么刷新
- 我用js创建了一个input,包含onblur事件,就会提示尚未实现这个错误
- 100分求一个简单的问题,请高手进来
- 调用JS无法显示的问题
- js怎么做个用户登陆,登陆后可以显示用户的用户名
- 如何解码t=eval("String.fromCharCode("+t+")");
- 如何判断当前位置是在一个Frame而不是一个普通HTML Page中呢?
- ●==我曾经在这个版狂放了1000分,这次又要倾我所有了:603分==●
- js页面跳转想提交myIDDNum这个变量...
- 字符窜格式判断“前面只能输入数字,最后一位是字母”
我把 onclick 函数注册为 dbg.out 为什么得不到想要的结果呢?
document.getElementById('Layer1').onclick = dbg.out;
实际执行时alert(this.num)中的this指的是Layer1,
下面这样写
document.getElementById('Layer1').onclick = function(){dbg.out();}
alert(this.num)中的this才指的是Debug的实例。你可以将alert(this.num)改为alert(this.id)试一下就知道了。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>js问题</title>
<style type="text/css">
<!--
#Layer1 {
width:87px;
height:56px;
z-index:1;
background-color: #CCCCCC;
}
-->
</style>
</head>
<script>
function Debug(num){
this.num = num;
}this.out = function(){
alert(num);
//alert("dfdfdfsdfds");
}var dbg = new Debug(555);
var gjp = "hello world";
</script>
<body>
<!-- 如果直接写到div则可以正常显示 数字555
<div id="Layer1" onclick="dbg.out()">clickme</div>
-->
<div id="Layer1" >clickme</div>
<script>
document.getElementById('Layer1').onclick = dbg.out;
</script>
</body>
</html>
我修改了一下你的Debug函数。其中
this.out = function(){
alert(this.num);
}
改为
this.out = function(){
alert(num);
}
就可以达到你要的结果了。具体原因是JS是this的用法和一般的面向对象的用法有不同的地方。
在JS中this就是引用函数级的。所以你用this.num在你的out函数中没有定义。所以显示时undefine.
还有个小问题问一下 tjgjp()所写的
"this.out = function(){
alert(this.num);
}
改为
this.out = function(){
alert(num);
}"这样document.getElementById('Layer1').onclick = dbg.out;
就可以正确执行了 可是 num 只是一个对象构造时的参数, 而 dbg.out这个函数是被语法copy到Layer1对象中的(this的指向都被更换了)
他又怎么能知道num的存在的呢?可能问题提的有点没水平,请大家见谅, 谢谢
不过,我的那种方法就是单纯从静态方面考虑的,也就是用面向对象的方法看问题,这样不用容易引起混乱。毕竟JS是一种动态的非编译性的语言。所以它很灵活,所以一种结果,可以有很多种的表现形式。所以这也是JS的魅力所在。呵呵
[5wCntid]
adj.
wanted by the police 被通缉的