开发者

setInterval() not working after clearInterval() in this Javascript code

I have been ripping my hair off a couple of nights now with this problem:

I'm trying to create an expanding div with JavaScript. Here's the part of the HTML file:

<div id="bbc_div" class开发者_如何学Go="bbc_div" style="display:none; height:200px;">
<input type="button" value="Show BBC" id="bbc_button" onclick="onclickBBC('bbc_div')" />

And here's the magical non-working JavaScript file:

var maxHeight = 100;
var curHeight = 1;
var wait = 5;
var timerID = new Array();

function onclickBBC(obj) {
    if (document.getElementById(obj).style.display == "none") {
        slideDown(obj);
    } 
    else {
        document.getElementById(obj).style.display="none"
    }
}

function slideDown(obj) {
    document.getElementById(obj).style.height="1px";
    document.getElementById(obj).style.display="block";
    timerID[obj] = setInterval("slideDownExec(\"" + obj + "\")", wait);
    return;
}

function slideDownExec(obj) {
    if (curHeight <= maxHeight) {
        curHeight++;
        document.getElementById(obj).style.height=curHeight + "px";
    }
    else {
        endSlide(obj);
    }
    return;
}

function endSlide(obj) {
    clearInterval(timerID[obj]);
    return;
}

When I reload the page, div expands once to its right height. But, if I push the button without reloading page again after it has hided again, it doesn't work. display:block; works, but setInterval() isn't starting. So this happens after clearInterval() has executed. Why is clearInterval() killing my setInterval() permanently?


The timer is running, you just need to reset a variable:

    function slideDown(obj)
    {
        document.getElementById(obj).style.height = "1px";
        curHeight = 1;

I would use jQuery for this, it's a LOT easier.


You have an issue with curHeight not being set to 1 at the top of slideDown. If this doesn't happen, the if statement at the top of slideDownExec will only work the first time.

Additionally, does JavaScript allow non-integer array indexes?

> a['i'] = 4
4
> a
[]
> a['i']
4

What you're actually doing is adding a property called i to the array object. You might as well use an empty object rather than an array.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜