jquery:在选择更改时按名称调用函数 [英] jquery: Call function by name on select change
问题描述
我正在尝试按名称 .onchange
调用一个函数,但没有任何反应。当该属性在属性之后被描述时,它可以工作。
I'm trying to call a function by name .onchange
of a select but nothing happens. When the function is describled after the attribute, it works.
这不起作用
HTML:
<select id="numb">
<option value="1">1</option>
<option value="2">2</option>
</select>
脚本:
<script type="text/javascript">
$('#numb').change(testMessage);
</script>
<script type="text/javascript">
function testMessage(){
alert('Hello');
}
</script>
此工作
HTML:
<select id="numb">
<option value="1">1</option>
<option value="2">2</option>
</select>
脚本:
<script type="text/javascript">
$('#numb').change(function(){
alert('Hello')
});
</script>
编辑:
好的,对于那些说我要在同一个脚本中包含该功能的人。这是不可能的,因为 testMessage()
函数位于<$ c $中包含的外部 .js
脚本中c>< head> HTML。
Ok, for all those who said me to include the function on the same script. This is not possible because the testMessage()
function is in an external .js
script included on the <head>
of the HTML.
推荐答案
这是因为处理程序<$ c绑定到更改事件时,未定义$ c> testMessage 。
如果它位于相同的脚本上下文中,它应该可以工作,
It should work if it was in the same script context like below,
<script type="text/javascript">
$('#numb').change(testMessage);
function testMessage(){
alert('Hello');
}
</script>
内的代码< script>< / script>
从顶部逐行执行, testMessage
函数在第一个< script>< / script> <中不存在/ code>。
Code inside <script></script>
are executed one by one progressive from top and testMessage
function doesn't exist inside the first <script></script>
.
这里有几个选项,
-
把它放进去一个匿名函数,它将让您的脚本稍后解析
testMessage
函数。 [根据 Optimus Prime 回答]
Put it inside an anonymous function which will let your script to resolve the
testMessage
function later. [As suggested in Optimus Prime answer]
<script type="text/javascript">
$('#numb').change(function () {
testMessage
});
</script>
<script type="text/javascript">
function testMessage(){
alert('Hello');
}
</script>
包含 testMessage
脚本
上方的函数,它绑定testMessage,如下所示,
Include the script that has testMessage
function above the script
that binds the testMessage like below,
<script type="text/javascript">
function testMessage(){
alert('Hello');
}
</script>
<script type="text/javascript">
$('#numb').change(testMessage);
</script>
这篇关于jquery:在选择更改时按名称调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!