Reputation: 1
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
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
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
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
Reputation: 4869
try this:
$("#btn").on('click', function () {
while(arr[i])
alert(arr[i++]);
});
Upvotes: 0