-3

我想获取元素的 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>
4

2 回答 2

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);
        });
    };
}
于 2013-07-31T15:14:05.820 回答
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/ebifuji/3/edit

于 2013-07-31T15:22:51.013 回答