问题
my javascript in .php (static website) file doesn't work. I use there 3 other scripts and they do work, but not this one.
The situation is simple
The javascript is...
var myFile = document.getElementById('myFile');
myFile.addEventListener('change', function() {
alert(this.files[0].size);
});
and the HTML code in the PHP file is (stripped)
<form onsubmit="return anotherfunction();" action="sendForm.php" enctype="multipart/form-data" method="post">
<table>
<tr>
<td>Attach an image:</td>
<td> <input type="file" name="priloha[]" accept="image/*" /></td>
</tr>
</table>
</form>
And the javascript does nothing, it acts like it doesn't exist. I tried to use the JS in the header, below the header, in the body, in the TD of the input... I also tried using it in external .js file, nothing, doesn't work at all. I tried changing "change" to "click", didn't work neither. I tried to do this all day and I can't figure out what's wrong.
So I tried to do much simpler code to check what's wrong and it seems like "change" or "onchange" - the second line of the JS doesn't work.
I also tried to specify HTML5 doctype, doesn't do a thing.
My extra .html file to try even simpler code looks like this and of course doesn't work...
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table>
<tr>
<td>Input field for click popup:</td>
<td>
<script type="text/javascript">
var input = document.getElementById('input');
input.addEventListener('click', function() {
alert("Hello");
});
</script>
<input type="text" id="input" />
</td>
</tr>
<table>
</body>
</html>
Help me please, I don't really know what's this... I forgot to mention, I tried different browsers - Opera 12.15, latest FF and Chrome, didn't work in any case. But it works in fiddle... thanks for any help in advance
回答1:
Put the script right at the end of the body, right before the </body>
end tag.
Scripts are loaded synchronously where they are placed, so any script put in before the element in question will not be aware of the element's existence.
Also, what Igor said.
回答2:
You don't have a DOM element with id "myFile" in html that you included.
来源:https://stackoverflow.com/questions/16927447/very-simple-javascript-doesnt-work-at-all