Javascript 仅当鼠标悬停2秒时进行AJAX调用
我有一个AJAX调用,如果我在某个元素上鼠标移动了2秒钟,我只需要做什么,否则就不需要做调用。我尝试使用setTimeout,但它无论如何都会打电话。我怎样才能做到这一点 这是我的密码:Javascript 仅当鼠标悬停2秒时进行AJAX调用,javascript,ajax,Javascript,Ajax,我有一个AJAX调用,如果我在某个元素上鼠标移动了2秒钟,我只需要做什么,否则就不需要做调用。我尝试使用setTimeout,但它无论如何都会打电话。我怎样才能做到这一点 这是我的密码: $('tr').mouseenter(function(){ $( this ).next("#ticket_summary").show(); var context = $( this ).next("#ticket_summary"); var ticket_id = $( th
$('tr').mouseenter(function(){
$( this ).next("#ticket_summary").show();
var context = $( this ).next("#ticket_summary");
var ticket_id = $( this ).next("#ticket_summary").data("id");
var url = "/support/ticket_description/" + ticket_id.toString();
console.log(url);
setTimeout(function(){
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(data) {
context.find('#ticket_summary_description').html(data[1]['fields']['text']);
context.find('#ticket_summary_last_comment').html(data[2]['fields']['text']);
},
error: function(data) {
context.find('#ticket_summary_description').html('error');
context.find('#ticket_summary_last_comment').html('error');
}
});
}, 2000);
});
问题是,如果用户离开,您必须使用
clearTimeout
取消超时
- 要检测用户何时“取消悬停”,请使用:
- 只处理一次我们使用的事件
- 要取消超时,请使用:
$('.the-element').on('mouseenter', function (e) {
var timeout = setTimeout(function () { ... }, 2000 );
$(e.target).one('mouseleave', function () {
clearTimeout(timeout)'
});
});
问题是,如果用户离开,您必须使用
clearTimeout
取消超时
- 要检测用户何时“取消悬停”,请使用:
- 只处理一次我们使用的事件
- 要取消超时,请使用:
$('.the-element').on('mouseenter', function (e) {
var timeout = setTimeout(function () { ... }, 2000 );
$(e.target).one('mouseleave', function () {
clearTimeout(timeout)'
});
});
我想这会管用的 HTML:
<a id='test'>LINK</a>
$("#test").mouseenter(function(){
setTimeout(function(){
$.ajax({
url:"test.php",
success:function(){
alert("success");
},
error:function(){
alert("ERROR");
}
});
},5000);
});
jsFiddle:
<a id='test'>LINK</a>
$("#test").mouseenter(function(){
setTimeout(function(){
$.ajax({
url:"test.php",
success:function(){
alert("success");
},
error:function(){
alert("ERROR");
}
});
},5000);
});
我认为这会奏效 HTML:
<a id='test'>LINK</a>
$("#test").mouseenter(function(){
setTimeout(function(){
$.ajax({
url:"test.php",
success:function(){
alert("success");
},
error:function(){
alert("ERROR");
}
});
},5000);
});
jsFiddle:
<a id='test'>LINK</a>
$("#test").mouseenter(function(){
setTimeout(function(){
$.ajax({
url:"test.php",
success:function(){
alert("success");
},
error:function(){
alert("ERROR");
}
});
},5000);
});
在这里寻找一些建议:在这里寻找一些建议: