user2725622
user2725622

Reputation: 1

JQuery Click() function executes only once

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.

Upvotes: 0

Views: 1490

Answers (4)

bfavaretto
bfavaretto

Reputation: 71908

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

Upvotes: 1

Rong Zhao
Rong Zhao

Reputation: 318

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++]);
});

Upvotes: 0

PSL
PSL

Reputation: 123739

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++]);
 });

Upvotes: 3

CIRCLE
CIRCLE

Reputation: 4869

try this:

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

Upvotes: 0

Related Questions