[英]SetTimeout not executing for on mousedown/touchstart function
小提琴-http: //jsbin.com/AYeFEHi/1/edit
谁能解释为什么这行不通? (在Linux上运行Chromium)
我试图仅在按钮按下2秒钟时执行警报框,否则就无法清除超时功能。
<!DOCTYPE html>
<html>
<head>
<title>Testing onmousedown setTimeout alert</title>
<meta charset='utf-8'>
<meta name='viewport' content='initial-scale=1.0'>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.min.js'></script>
<script type='text/javascript'>
function call() {
alert('Hello World!');
}
$("#alertme").on('mousedown touchstart', function() {
setTimeout(call, 2000);
});
$("#alertme").on('mouseup touchend', function() {
clearTimeout(call, 0);
});
</script>
</head>
<body>
<button id="alertme">Alert me</button>
</body>
</html>
这不是clearTimeout
工作方式。 您需要将setTimeout
返回的值传递给它。
function call() {
alert('Hello World!');
}
var callTimeout = null; // hold onto the identifier for the timeout
$("#alertme").on('mousedown touchstart', function() {
callTimeout = setTimeout(call, 2000);
});
$("#alertme").on('mouseup touchend', function() {
clearTimeout(callTimeout); // clear the timeout identifier we saved.
});
您可能希望将其包装在jQuery页面就绪回调中,以便脚本可以在页面上的任何位置:
$(function() {
var call = function() {
alert('Hello World!');
}
var callTimeout = null;
$("#alertme").on('mousedown touchstart', function() {
callTimeout = setTimeout(call, 2000);
});
$("#alertme").on('mouseup touchend', function() {
clearTimeout(callTimeout);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.