Why Array gives null outside script onclick event in htm5? The others variables works correctly.
<!DOCTYPE html>
<html>
<head>
<title>Array</title>
<script>
var list = new Array("andrea", "matteo", "marco");
var x = "andrea";
</script>
</head>
<body>
<input type="button" value="click" onclick="alert(list[0]);">
</body>
</html>
2
Answers
It’s because
list
is not in scope of youronclick
attribute. You can prefix it withwindow
to target it directly:Better still, you should avoid using
onX
attributes wherever possible. Use unobtrusive event handlers bound in JS. You can also use this method to avoid using global variables:You should wait for the DOM to be fully loaded before trying to access the
list
array. You can use theDOMContentLoaded
event for this purpose.Here’s an updated version of your code: