如何在javascript中从子函数访问var?

时间:2013-07-31 15:04:34

标签: javascript jquery oop

我想获取元素的id并希望将它用于另一个子函数

function example(id) {
    var me = this;
    this.pro = ID
    this.code = function () {
        setTimeout(function () {
            alert(ID)
        }, 20)
    }
    this.validate = function () {
        $('.' + id).keyup(function (e) {
            var ID = this.id;
            if (e.keyCode == 13) me.code()
        })
    }
}

<input type="text" class="test" id="1" />
<input type="text" class="test1" id="2" />

<script type="text/javascript">
    var test = new example('test')
    var test1 = new example('test1')
    test.validate()
    test1.validate()
</script>

2 个答案:

答案 0 :(得分:1)

使用pro属性

function example(id) {
    var me = this;
    this.pro = null;
    this.code = function () {
        setTimeout(function () {
            alert(me.pro);
        }, 20);
    };
    this.validate = function () {
        $('.' + id).keyup(function (e) {
            me.pro = this.id;
            if (e.keyCode == 13) me.code();
        });
    };
}

或使其成为该函数的参数:

function example(id) {
    var me = this;
    this.code = function (ID) {
        setTimeout(function () {
            alert(ID);
        }, 20);
    };
    this.validate = function () {
        $('.' + id).keyup(function (e) {
            var ID = this.id;
            if (e.keyCode == 13) me.code(ID);
        });
    };
}

答案 1 :(得分:0)

只需取出当前元素的id,然后在他周围玩耍。

function example(id) {
    var currentId = $('.'+id).attr('id');
    this.validate = function () {
        $('.'+id).keyup(function (e) {
          if (e.keyCode == 13) {
            console.log(currentId);
          }  
        });
    };
}

$(document).ready(function(){
    var test = new example('test');
    var test1 = new example('test1');
    test.validate();
    test1.validate();
});

JSBin:http://jsbin.com/ebifuj/3/edit