JavaScript中的onclick事件函数 [英] onclick event function in JavaScript

查看:128
本文介绍了JavaScript中的onclick事件函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在带按钮的HTML页面中有一些JavaScript代码.我有一个名为click()的函数,该函数处理按钮的onClick事件.该按钮的代码如下:

I have some JavaScript code in an HTML page with a button. I have a function called click() that handles the onClick event of the button. The code for the button is as follows:

<input type="button" onClick="click()">button text</input>  

问题是单击按钮时未调用该函数.我在这里做什么错了?

The problem is that when the button is clicked, the function is not called. What am I doing wrong here?

推荐答案

两个观察结果:

  1. 您应该写

  1. You should write

<input type="button" value="button text" />

代替

<input type="button">button text</input>

  • 您应该重命名您的函数.函数click()已经在按钮上定义(它模拟点击),并且比您的方法具有更高的优先级.

  • You should rename your function. The function click() is already defined on a button (it simulates a click), and gets a higher priority then your method.

    请注意,这里有一些完全错误的建议,您不应该在这些建议上花费太多时间:

    Note that there are a couple of suggestions here that are plain wrong, and you shouldn't spend to much time on them:

    • 请勿使用onclick="javascript:myfunc()".仅在超链接的href属性内使用javascript:前缀:<a href="javascript:myfunc()">.
    • 您不必以分号结尾. onclick="foo()"onclick="foo();"都可以正常工作.
    • HTML中的
    • 事件属性不区分大小写,因此onclickonClickONCLICK均有效.通常将属性写为小写:onclick. 请注意,javascript本身是区分大小写的,因此,如果编写document.getElementById("...").onclick = ...,则必须全部为小写字母.
    • Do not use onclick="javascript:myfunc()". Only use the javascript: prefix inside the href attribute of a hyperlink: <a href="javascript:myfunc()">.
    • You don't have to end with a semicolon. onclick="foo()" and onclick="foo();" both work just fine.
    • Event attributes in HTML are not case sensitive, so onclick, onClick and ONCLICK all work. It is common practice to write attributes in lowercase: onclick. note that javascript itself is case sensitive, so if you write document.getElementById("...").onclick = ..., then it must be all lowercase.

    这篇关于JavaScript中的onclick事件函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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