onclick无法使用按钮 [英] onclick not working with button

查看:295
本文介绍了onclick无法使用按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按下搜索按钮使javascript功能工作但功能似乎没有运行。请指导。 小提琴

I am trying to make a javascript function work on pressing search button but the function doesnt seem to run. Please guide. Fiddle.

<form action="" method="get" id="searchform" >
    <input name="q" type="text" id="search" size="32" maxlength="128" class="txt"/>
    <input type="submit" id="hit" value="Search" onclick="myFunction()" class="btn"/>
</form>

继承人JS,

function myFunction() {
 alert("I am an alert box!");
}


推荐答案

你已经将函数包装好了正文, onLoad ,只需将其更改为无包装 - < head> 。请参见这个小提琴。

You have wrapped the function in the body, onLoad, just change it to no wrap - in <head>. See this fiddle.

function myFunction() {
    alert("I am an alert box!");
}

};
^^

您还有一个额外的};

更新:

这种情况发生因为:


  • 如果函数放在 $(文件).ready ,然后它只能在ready回调中使用(以及在内部对象中)。你不能在外面引用它。

  • if the function is place inside $(document).ready, then it can only be used within the ready callback (and in the inner objects). You can't reference it outside.

但是如果你把它放在就绪函数之外那么它就会获得全局范围,即你可以从任何地方打电话。

but if you are placing it outside the ready function then it gets global scope, i.e. you can call it from anywhere.

这篇关于onclick无法使用按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆