Jquery使用on绑定的事件函数中使用构造函数的原型方法

var Obj = function( target ) {
    this.target = $(target);
    this.num = 0;
    this.setNum = setNum;
}
Obj.prototype.display = function() {
    alert( this.num );
}
function setNum() {
    var $t = this.target;
    $t.on('click', 'a', function(e) {
        使this.num的值为a的value;
        这里执行原型函数display;
    });
}

应该怎么写?

阅读 2.9k
2 个回答
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
</head>
<body>
    <div class="haha">哈哈</div>
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
var Obj = function( target ) {
    this.target = $(target);
    this.num = 0;
    this.setNum = setNum;
}
Obj.prototype.display = function() {
    alert( this.num );
}
function setNum() {
    var $t = this.target;
    var _this=this;
    console.log($t);
    $t.on('click',{a:"hihihihi"},function(e) {
        // 使this.num的值为a的value;
        // 这里执行原型函数display;
        console.log(e);
        _this.num=e.data.a;
        _this.display();
        console.log(_this);
    });
}    

var dom=new Obj(".haha");
console.log(dom);
dom.setNum();

</script>

这种不用写成这样,你写个具名的功能function,然后那个num变量是可以用$.data绑到相应的dom上的,比如可以:

// 具名事件处理
function setNum() {
    var $this = $(this);
    var val = $this.attr('value');
    $this.data('num', val);
    console.info("num: " + $this.data("num"));
}

最后再给这个处理绑下事件就行了。


还是加个符合题意的写法吧:

var Obj = function( target ) {
    this.target = $(target);
    this.num = 0;
}
Obj.prototype = {
    constructor: Obj,
    display: function() {
        alert( this.num );
    },
    setNum() {
        var $t = this.target;
        $t.on('click', 'a', function(e) {
        // 使this.num的值为a的value
        this.num = $(this).attr('value');
        // 这里执行原型函数display
        this.display();
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题