Javascript 在HTML中为特定id调用JS函数

Javascript 在HTML中为特定id调用JS函数,javascript,jquery,html,onclick,Javascript,Jquery,Html,Onclick,在JS文件名中,我有以下函数作为hello.JS在JS文件夹中 JS function hello(){ alert('hello world !); } HTML <!DOCTYPE HTML> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

在JS文件名中,我有以下函数作为hello.JSJS文件夹中

JS

function hello(){
    alert('hello world !);
}
HTML

<!DOCTYPE HTML>
<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="js/hello.js"></script>
        <script>
            $(function() {
                $("#hello").hello();
            });
        </script>
    </head>
    <body>
        <button type="button" id="hello">Click Me!</button> 
    </body>
    </html>
<button type="button" id="hello" onclick="hello();">Click Me!</button> 

$(函数(){
$(“#你好”).hello();
});
点击我!
如何将
hello()
函数附加到带有
id=“hello”
的按钮上?我做错了什么,但我找不到什么

编辑:为了完整起见,我建议阅读所有答案

Edit2:这个问题的目的是澄清将函数附加到html上特定元素的一般方法。按钮和单击交互就是一个例子。

用于绑定事件处理程序

$("#hello").on('click', hello);

您可能正在使用
hello
作为处理程序绑定id为
hello
的按钮上的
click
事件

$("#hello").click(hello);
纯javascript:

var elm=document.getElementById("hello");
elm.onclick= function{ hello();};
Jquery:

$("#hello").click(hello() );

使用HTML或DOM处理事件的方法有很多

用HTML定义它

<!DOCTYPE HTML>
<html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script type="text/javascript" src="js/hello.js"></script>
        <script>
            $(function() {
                $("#hello").hello();
            });
        </script>
    </head>
    <body>
        <button type="button" id="hello">Click Me!</button> 
    </body>
    </html>
<button type="button" id="hello" onclick="hello();">Click Me!</button> 
使用Javascript将函数附加到事件处理程序:

var el = document.getElementById("hello");
    if (el.addEventListener)
        el.addEventListener("click", hello, false);
    else if (el.attachEvent)
        el.attachEvent('onclick', hello);

function hello(){
            alert("inside hello function");
}
有用的链接


您当前正试图以jQuery扩展方法调用hello。您可以将其编写为jQuery hello插件,但只需使用
单击
即可:)对于一个简单的
单击
处理程序案例,为什么要在上使用
?只会使代码变长,在这里没有额外的收益。您很清楚,
click
只是
的简写。on(“click”,handler)
。那么,为什么不告诉OP使用
.on()
,因为正如我所说的,它更长(准确地说是长6个字符)。。。JS代码的目标之一是简洁:Pwell,
上的
不是一个本机javascript函数,在这两个示例中,函数
hello
都被调用,而不是作为参数传递。不确定为什么这个答案会有任何上行投票,因为它不会像写的那样工作。请更正您的示例:)