选择onclick onchange不起作用 [英] select onclick onchange not working
问题描述
我一直试图弄清楚现在几个小时,我不明白为什么我的JavaScript不工作。我有一个像这样的选择按钮
< select onclick =populateList()>
< option> 1< / option>
< option> 2< / option>
< / select>
我的Javascript位于同一个文件夹中,链接为:
< script src =script.js>< / script>
在该文件中,函数非常简单。 Just:
函数populateList(){
console.log(Test);
}
它不起作用。任何想法为什么?
编辑:
我试过做onchange,onchange(), onclick,onclick(),onClick()等。仍然没有。
Edit2:我没有改变一件事,但它开始工作。谢谢你们。非常喜欢。
编辑3:Nevermind。我至少确定它在脚本直接在html中,但不在script.js中时可以工作
解决方案尝试使用此代码,在 JSFiddle 中工作:
JS部分:
$ b
函数populateList(){
alert(测试);
}
HTML部分:
< select onchange =populateList();>
< option> 1< / option>
< option> 2< / option>
编辑:
正如您在编辑中所说的那样,它在脚本中工作,但不是 JS
。我猜这是因为它被包装在
onLoad
或 onDomReady
函数中 - 请参阅:
请注意,jsfiddle仅在Framework设置为'no wrap(head或body)'时才有效,而不是 onDomReady
。
如果在 js
file你的代码被包装在类似于
$(document).ready(function(){
函数populateList(){
alert(Test);
}
});
这不起作用。尝试从中删除它,并将它放置在附加的 js
文件的最上面,并附上 js
文件在同一个位置,你现在已经在你的脚本中编写了 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 My Javascript is in the same folder and is linked as: In that file, the function is so simple. Just: 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: HTML part:
Edit: As you said in your edit, it works when it's in the script but not the Note that that jsfiddle only works when Framework is set to 'no wrap (head or body)', and not If in your It won't work. Try removing it from that and placing it at the very top by itself in your attached Here's the code in an actual 这篇关于选择onclick onchange不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! html
和 js
文件,除了 onclick
到 onchange $ c $在
html
和 console.log
到 alert
在 js
中。完美工作。 <select onclick="populateList()">
<option>1</option>
<option>2</option>
</select>
<script src="script.js"></script>
function populateList() {
console.log("Test");
}
function populateList(){
alert("Test");
}
<select onchange="populateList();">
<option>1</option>
<option>2</option>
</select>
JS
. The reason I can guess for this is it's wrapped in an onLoad
or onDomReady
function - see this:onDomReady
or onLoad
.js
file your code is wrapped in something like$(document).ready(function(){
function populateList(){
alert("Test");
}
});
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?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.