按照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

解决方案 »

  1.   

    执行这个o.init("d")事件的时候,rel被重新赋值了
    可以考虑用构造函数来实现
      

  2.   

    但是c函数还在别的方法里需要调用
    !function(){
        o={};
        var rel;
        function c(){
            alert(rel);
        };
        o.init=function(r){
            rel=r;
            document.getElementById(rel).onclick=c;
        };
        o.foo=function(){
           c();
           //TODO
        }
    }();
    这样的话怎么办呢?
      

  3.   

    //把rel参数传递进去,修改c函数!function(){
        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
      

  4.   

    你这种要求做成类的形式就好了。 <html>
        <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>
      

  5.   

    var aa = function(r){
    var o = {};
    o.rel = r;
    function c(){
    alert(o.rel);
    }
    ~function(){
            document.getElementById(o.rel).onclick = c;
    }()
    }
    aa('c');
    aa('d');