onchange $ c $在 html
和 console.log
到 alert
在 js
中。完美工作。
I've been trying to figure this out for hours now and I can't understand why my javascript isn't working. I have a select button like this
<select onclick="populateList()">
<option>1</option>
<option>2</option>
</select>
My Javascript is in the same folder and is linked as:
<script src="script.js"></script>
In that file, the function is so simple. Just:
function populateList() {
console.log("Test");
}
And it won't work. Any ideas as to why?
EDIT:
I've tried doing the onchange, onchange(), onclick, onclick(), onClick(), ect. and still nothing.
Edit2:I didn't change a thing but it started working. Thank you all. Much love.
Edit 3: Nevermind. I've determined at least that it works when the script is directly in the html but not when it's in script.js
解决方案
Try using this code, working in JSFiddle:
JS part:
function populateList(){
alert("Test");
}
HTML part:
<select onchange="populateList();">
<option>1</option>
<option>2</option>
</select>
Edit:
As you said in your edit, it works when it's in the script but not the JS
. The reason I can guess for this is it's wrapped in an onLoad
or onDomReady
function - see this:
http://jsfiddle.net/xUk5K/1/
Note that that jsfiddle only works when Framework is set to 'no wrap (head or body)', and not onDomReady
or onLoad
.
If in your js
file your code is wrapped in something like
$(document).ready(function(){
function populateList(){
alert("Test");
}
});
It won't work. Try removing it from that and placing it at the very top by itself in your attached js
file and attach the js
file in the very same location you're now hard coding the js
in your script - is it working now?
Here's the code in an actual html
and js
file, with absolutely nothing changed except onclick
to onchange
in the html
and console.log
to alert
in the js
. Working perfectly.
这篇关于选择onclick onchange不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!