How to use Javascript timeout to apply jQuery addClass
Here is my entire document:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.highlighted { color:green; font-weight:bold; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function itemHighlight(n)
{
$(function() {
$("ul > li:eq("+n+")").addClass("highlighted");
});
}
NumofLi = $('li').length;
for(i = 0; i < NumofLi; i++) {
var timeoutvar = $("ul > li:eq("+i+")").attr('data-time');
setTimeout("itemHighlight("+i+")", timeoutvar);
}
});
</script>
</head>
<body>
<ul>
<li data-time="4000">foo</li>
<li data-time="5000">foo</li>
<li data-time="9000">foo</li>
<li data-time="11000">foo</li>
<li data-time="15000">foo</li>
</ul>
</body>
</html>
I would like the li's to h开发者_开发百科ave the class "highlighted" added after their corresponding 'data-time' milliseconds.
Try this:
$(function(){
$('li').map(function(){
var _this = $(this);
setTimeout(function(){
_this.addClass('highlighted');
},Number(_this.data('time')));
});
});
Working example: http://jsfiddle.net/AlienWebguy/dzAGn/2/
$(document).ready(function()
{
#("ul li")each(function()
{
var timeOut = Number( $(this).attr("data-time") );
var element = $(this);
setTimeout(function()
{
element.addClass('highlighted');
}, timeOut);
});
});
JsFiddle example
$(function(){
$('li').each(function(){
var _this = $(this);
setTimeout($.proxy(timeout, _this), Number(_this.data('time')));
});
function timeout(){
this.addClass('highlighted')
}
});
Your functions is inside $(document).ready(...)
. Put it outside:
<script type="text/javascript">
$(document).ready(function() {
NumofLi = $('li').length;
for(i = 0; i < NumofLi; i++) {
var timeoutvar = $("ul > li:eq("+i+")").attr('data-time');
setTimeout("itemHighlight("+i+")", timeoutvar);
}
});
function itemHighlight(n) {
$(function() {
$("ul > li:eq("+n+")").addClass("highlighted");
});
}
</script>
精彩评论