我想在setInvterval中更改div的背景图片,但无法弄清楚如何。这是代码:
$('.thumbnail').on({
'mouseenter': function(){
var thumbs = $(this).attr('data-num-thumbs');
var thumb_url = $(this).css('background-image');
console.log(thumb_url);
var i = 1;
setInterval(function(){
var new_thumb_url = thumb_url.replace(/\d{1,2}\.jpg/gi, i + '.jpg');
console.log(new_thumb_url);
$(this).css('background-image', new_thumb_url);
i++;
if(i > 10) i = 1;
}, 3000);
});
});
这就是div
的样子:
<div data-num-thumbs="17" class="thumbnail" style="background: url('http://site/img/11.jpg') no-repeat;"></div>
答案 0 :(得分:1)
看起来$(this)
内的setInterval()
正在映射到其他内容,请尝试此操作
$('.thumbnail').on({
'mouseenter': function(){
$this=$(this); //store $(this) in a local var
var thumbs = $(this).attr('data-num-thumbs');
var thumb_url = $(this).css('background-image');
console.log(thumb_url);
var i = 1;
setInterval(function(){
var new_thumb_url = thumb_url.replace(/\d{1,2}\.jpg/gi, i + '.jpg');
console.log(new_thumb_url);
//$(this).css('background-image', new_thumb_url);
$this.css('background-image', new_thumb_url);
i++;
if(i > 10) i = 1;
}, 3000);
}
});
快乐编码:)