鍍金池/ 問答/Java  PHP  Python  網(wǎng)絡(luò)安全  HTML/ zepto長按事件怎么得到當(dāng)前this,發(fā)下代碼

zepto長按事件怎么得到當(dāng)前this,發(fā)下代碼

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no" />
    <style>
        #test{
            width: 100%;
            height: 100px;
            background-color: red;
        }
    </style>
</head>
<body>
<div id="test">212121</div>
<script src="https://cdn.bootcss.com/zepto/1.2.0/zepto.min.js"></script>
<script>
    $.fn.longPress = function(fn) {
        var timeout = undefined;
        var $this = this;
        for(var i = 0;i<$this.length;i++){
            $this[i].addEventListener('touchstart', function(event) {
                timeout = setTimeout(fn, 800);  //長按時間超過800ms,則執(zhí)行傳入的方法
            }, false);
            $this[i].addEventListener('touchend', function(event) {
                clearTimeout(timeout);  //長按時間少于800ms,不會執(zhí)行傳入的方法
            }, false);
        }
    }
    $('#test').longPress(function(){
        //do something...
        console.log(this);
        console.log($(this));
       
    });
</script>
</body>
</html>
回答
編輯回答
情已空

timeout = setTimeout(function(){

fn.call($this);

},800)

2017年5月15日 00:06
編輯回答
賤人曾

我猜你想綁定的是這個 this,用 bind 就可以:

timeout = setTimeout(fn.bind(this), 800)

2017年3月4日 18:24