如果用户单击Javascript或Jquery中的div,则停止函数的执行
当用户加载一个页面时,我触发一个“计时器”,它将在8秒后显示消息。 我的问题是,如果用户在这8秒钟之前单击div#contentAfterIntro,我想阻止显示消息如果用户单击Javascript或Jquery中的div,则停止函数的执行,javascript,jquery,Javascript,Jquery,当用户加载一个页面时,我触发一个“计时器”,它将在8秒后显示消息。 我的问题是,如果用户在这8秒钟之前单击div#contentAfterIntro,我想阻止显示消息 xoxo(); function xoxo(e) { setTimeout(showMessage, 8000); $("#contentAfterIntro").on('click', function(e) { e.stopPropagation(); }); } function showMes
xoxo();
function xoxo(e) {
setTimeout(showMessage, 8000);
$("#contentAfterIntro").on('click', function(e) {
e.stopPropagation();
});
}
function showMessage() {
$('#msg').addClass('visible');
console.log('show msg');
}
上面的代码不起作用。在我的测试中,即使我在8秒钟之前单击,也会显示消息
如何实现此目的?
setTimeout
返回一个id,您可以使用该id取消超时:
xoxo();
function xoxo(e) {
var id = setTimeout(showMessage, 8000);
$("#contentAfterIntro").on('click', function(e) {
e.stopPropagation();
clearTimeout(id); // <--- clear timeout
});
}
function showMessage() {
$('#msg').addClass('visible');
console.log('show msg');
}
xoxo();
函数xoxo(e){
var id=setTimeout(showMessage,8000);
$(“#contentAfterIntro”)。在('click',函数(e){
e、 停止传播();
clearTimeout(id);//setTimeout
返回可用于取消超时的id:
xoxo();
function xoxo(e) {
var id = setTimeout(showMessage, 8000);
$("#contentAfterIntro").on('click', function(e) {
e.stopPropagation();
clearTimeout(id); // <--- clear timeout
});
}
function showMessage() {
$('#msg').addClass('visible');
console.log('show msg');
}
xoxo();
函数xoxo(e){
var id=setTimeout(showMessage,8000);
$(“#contentAfterIntro”)。在('click',函数(e){
e、 停止传播();
clearTimeout(id);//我现在就试试。如果我使用clearTimeout(id),我还需要e.stopPropagation()吗?stopPropagation
与超时无关,只与click事件有关。如果它只是用来尝试停止超时,那么你就不需要它。将在10分钟后接受,因为它阻止我现在这样做:)我现在就来试试。如果我使用cleartimeout(id),我还需要e.stopPropagation()吗?stopPropagation
与超时无关,只与click事件有关。如果它只是用来尝试停止超时,那么您就不需要它。将在10分钟后接受,因为它阻止我立即执行:)