我试图在悬停一秒钟后触发一个动作(动态创建元素),如果光标移出,我想setTimeout = null;
$("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;
}
})
});
答案 0 :(得分:0)
如何尝试注册动态悬停处理程序是错误的,您可以将事件委派与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").on({
mouseenter: function(ev) {
var $this = $(this);
var timeoutId = window.setTimeout(function() {
$this.removeData('timeoutId');
//do your stuff here
console.log($this.attr('id'));
}, 1000);
$this.data('timeoutId', timeoutId);
},
mouseleave: function(ev) {
var $this = $(this),
timeoutId = $this.data('timeoutId');;
$this.removeData('timeoutId');
clearTimeout(timeoutId);
}
}, ".dropDown ul li");
//add more dynamic items
for (var i = 4; i < 7; i++) {
$('<li />', {
id: i,
text: i
}).appendTo('ul')
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<nav>
<div class="dropDown">
<ul>
<li id="1">1</li>
<li id="2">2</li>
<li id="3">3</li>
</ul>
</div>
</nav>
&#13;