[英]Show array element on button click using javascript
I have an array of strings, you can see below and i want to alert each element one by one on button click: 我有一个字符串数组,您可以在下面看到,我想在单击按钮时逐个提醒每个元素:
function mysimplefunc() {
var i = 0;
var array = ["a", "b", "c", "d"];
if (array.length < 4)
{
var str = array[i];
i++;
alert(str);
}
}
below is asp code: 下面是asp代码:
<asp:Button ID="btn_SHow" runat="server" Text="Show Elements" OnClientClick="mysimplefunc();" />
But its not working. 但是它不起作用。
the if loop
will not working since array length is 4 由于数组长度为4,因此if loop
将不起作用
and u must use for loop
inorder to iterate each element..!! 而且您必须使用for loop
才能迭代每个元素。
for ( i=0;i<array.length;i++)
{
var str = array[i];
alert(str);
}
Try this function. 试试这个功能。 This handles creating the array counter (i) as a global variable, and any number of items can be included in the array, not just four. 这可以将数组计数器(i)创建为全局变量,并且数组中可以包含任意数量的项目,而不仅仅是四个。
function mysimplefunc() {
var array = ["a", "b", "c", "d"];
if (typeof i == "undefined") {i = 0};
alert(array[i++]);
if (i == array.length) {i = 0}
}
function mysimplefunc() {
var i = 0; //declare & initialise a integer variable used for loop counter.
var array = ["a", "b", "c", "d"]; //Create an string array of 4 elements with name array
var arrLength=array.length; //find the length of array elements
for (;i<arrLength;) //iterate over the array elements upto last element
{
var str = array[i]; //take first element from array
i++; //increment the loop counter
alert(str);//popup the small window with values present in array
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.