0

In the following code, CLICK() method runs only one time:

<!DOCTYPE html>
<html>
<head>
    <script src="jquery-1.10.2.min.js"></script>
    <script>
    $(function(){
        var arr = ["test1", "test2", "test3"];
        var i=0;

        $("#btn").click( function () {
            while(arr[i])
                alert(arr[i++]);
        });

    });
    </script>
</head>

<body> 
    <div id="btn">Click Me</div>
</body>

</html>

Whats the problem? I read all the other subjects but didn't help.

4 Answers 4

3

It does: - Just reset your i to 0. In your handler the condition fails second time because your i becomes array.length from your previous execution and it fails, since there is no item at arr[array.length] i.e3 in your case.

    $("#btn").click(function () {
       while(arr[i])
            alert(arr[i++]);
        i = 0; //here reset it

    });

or just move it to the scope of the function.

$("#btn").click(function () {
        var i = 0;
           while(arr[i])
                alert(arr[i++]);
 });
Sign up to request clarification or add additional context in comments.

Comments

1

The click method runs on every click, but after the first one it doesn't enter while loop anymore, because i === 3.

Comments

0

try this:

$("#btn").on('click', function () {
            while(arr[i])
                alert(arr[i++]);
        });

Comments

0

I think the problem is caused by variable i, please move i to click function, such as:

$("#btn").bind('click', function(){
    var i = 0;
    while(arr[i])
        alert(arr[i++]);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.