按照1的改就好了,闭包没做好 !function () {
o = {};
var rel;
/* function c() {
alert(rel);
};*/
o.init = function (r) {
//rel = r;
function c() {
rel = r;
alert(rel);
}
document.getElementById(r).onclick = c;
};
} ();
o.init("c"); //d
o.init("d"); //d
o = {};
var rel;
/* function c() {
alert(rel);
};*/
o.init = function (r) {
//rel = r;
function c() {
rel = r;
alert(rel);
}
document.getElementById(r).onclick = c;
};
} ();
o.init("c"); //d
o.init("d"); //d
解决方案 »
- 一段js,通常情况下没什么问题,但在某个时候后台接值时会报userid未定义或输出+userid+,求解
- js图片滚动问题
- firefox对js使用问题,为什么在浏览器上按上一部按钮后倒上一页js就失效了
- 关于jquery $(this)和 this的区别
- 一段日期代码的痛
- 隐藏cell的问题
- Unable to get image data from canvas because the canvas has been tainted by cros
- 求助(关于条件判断)
- 请高手指点把javascript数组数据保存在application的方法
- JS函数总是提示未定义!!
- 关于JS为另一个页面文本框
- 谷歌浏览器中,上下键会影响文本框光标的位置怎么解决
可以考虑用构造函数来实现
!function(){
o={};
var rel;
function c(){
alert(rel);
};
o.init=function(r){
rel=r;
document.getElementById(rel).onclick=c;
};
o.foo=function(){
c();
//TODO
}
}();
这样的话怎么办呢?
o={};
var rel;
function c(){
if(arguments[0] !=='undefined')
alert(arguments[0]);
else
alert(rel);
};
o.init=function(r){
rel=r;
document.getElementById(rel).onclick=(function(arg){return function(){c(arg)};}(rel));
};
o.foo=function(){
c();
//TODO
}
}();
o.init("c"); //d
o.init("d"); //d
<body>
<div id="a" style="height:300px;width:50%;float:left;background-color:rgb(255,69,0)"></div>
<div id="b" style="height:300px;width:50%;float:right;background-color:rgb(135,206,250)"></div>
<div id="c" style="height:300px;width:50%;float:left;background-color:rgb(255,255,0)"></div>
<div id="d" style="height:300px;width:50%;float:right;background-color:rgb(255,206,250)"></div>
</body>
<script language="javascript">
function func(r) {
this.rel = r;
var me = this;
document.getElementById(r).onclick = function () { me.c(); }
this.foo();
}
func.prototype.c = function () { alert(this.rel); }
func.prototype.foo=function(){alert(this.rel)} var c = new func('c');
var d = new func('d');
</script>
</html>
var o = {};
o.rel = r;
function c(){
alert(o.rel);
}
~function(){
document.getElementById(o.rel).onclick = c;
}()
}
aa('c');
aa('d');