Javascript jQuery-悬停在动态创建的元素setTimeout上
我试图在悬停一秒钟后触发一个动作(元素是动态创建的),如果光标移出,我想设置timeout=nullJavascript jQuery-悬停在动态创建的元素setTimeout上,javascript,jquery,Javascript,Jquery,我试图在悬停一秒钟后触发一个动作(元素是动态创建的),如果光标移出,我想设置timeout=null $("nav").on("mouseover", ".dropDown ul li", function (ev) { var id = ev.target.id, timeoutId = null; $("#" + id).hover(function () { if (timeoutId === null) { time
$("nav").on("mouseover", ".dropDown ul li", function (ev) {
var id = ev.target.id,
timeoutId = null;
$("#" + id).hover(function () {
if (timeoutId === null) {
timeoutId = window.setTimeout(function () {
timeoutId = null;
alert(id);
}, 1000);
}
},
function () {
if (timeoutId !== null) {
window.clearTimeout(timeoutId);
timeoutId = null;
}
})
});
尝试注册动态悬停处理程序的方式是错误的,您可以将事件委派与
mouseenter
和mouserleave事件一起使用,如
$("nav").on({
mouseenter: function (ev) {
var $this = $(this);
var timeoutId = window.setTimeout(function () {
console.log($this.attr('id'));
$this.removeData('timeoutId');
}, 1000);
$this.data('timeoutId', timeoutId);
},
mouseleave: function (ev) {
var $this = $(this),
timeoutId = $this.data('timeoutId');;
$this.removeData('timeoutId');
clearTimeout(timeoutId);
}
}, ".dropDown ul li");
$(“nav”)。在({
鼠标指针:功能(ev){
var$this=$(this);
var timeoutId=window.setTimeout(函数(){
$this.removeData('timeoutId');
//在这里做你的事
console.log($this.attr('id'));
}, 1000);
$this.data('timeoutId',timeoutId);
},
鼠标移动:功能(ev){
变量$this=$(this),
timeoutId=$this.data('timeoutId');;
$this.removeData('timeoutId');
clearTimeout(timeoutId);
}
},“.dropDown ul li”);
//添加更多动态项
对于(变量i=4;i<7;i++){
$(“”{
id:我,
正文:i
}).appendTo('ul')
}
- 1
- 2
- 3
jsfiddle或一些html代码在这里非常有用。问题是什么?将您的timeoutId
移出处理程序