javascript global array
I am having below html code and trying to add new values to global array by onchanging of javascript function.I am trying to do like below way.But it is giving javascript error开发者_如何学JAVAs.Please suggest anyone how to do this.
<html>
<head>
<script>
var list=[];
function getList(value){
list=list(value);
}
</script>
</head>
<body>
<tr>
<td>
<select name="test" onchange="getList(this)">
<option id="1" value="one">One</option>
<option id="2" value="two">two</option>
</select>
</td>
</tr>
<tr>
<td>
<select name="test1" onchange="getList(this)">
<option id="3" value="three">three</option>
<option id="4" value="four">four</option>
</select>
</td>
</tr>
</body>
</html>
Change your Javascript to the following
var list=new Array; ///this one way of declaring array in javascript
function getList(value){
list.push(value);//push function will insert values in the list array
}
Adding values to an array is quite simple, all you have to do is call the push(..) method.
Like so:
var list = [ ];
list.push(1);
console.info(list); // Outputs: [ 1 ]
- Mozilla array reference
- Mozilla array push reference
The easiest way to add a value to an array in JavaScript, it to use the push method (unless you need to support IE5):
function getList(value) {
list.push(value);
}
Two things:
In your case this would add references to the select elements to the list. That's most likely not what you want. What exactly do you want to add?
getListisn't really a suitable name for that.addToListwould be probably better.
You're currently passing the entire select element to your function, rather than the selected value. You can pass the selected value like this:
getList(this.options[this.selectedIndex].value)
Then you can use list.push(value) in your function to add the selected value to your array.
加载中,请稍侯......
精彩评论