javascript 为 HTML 中的特定 id 调用 JS 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31586512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 14:01:10  来源:igfitidea点击:

Call JS function for specific id in HTML

javascriptjqueryhtmlonclick

提问by hardstudent

I have below function in JS file name as hello.jsinside jsfolder.

我在 js 文件名中有以下函数作为hello.jsjs文件夹中。

JS

JS

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

HTML

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>

How do I attach the hello()function to the button with the id="hello"? I'm doing something wrong but I can't find what.

如何使用 将hello()功能附加到按钮上id="hello"?我做错了什么,但我找不到什么。

Edit :I recommend reading all answers for completeness.

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

Edit2:The purpose of this question was to clarify the general method of attaching functions to specific elements on html. The button and the click interaction was an example.

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

回答by Adil

You are probably looking to bind clickevent on button with id hellousing helloas handler

您可能希望使用作为处理程序的clickid绑定按钮上的事件hellohello

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

回答by Satpal

Use .on()to bind event handler.

使用.on()绑定的事件处理程序。

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

回答by Simpal Kumar

There are many ways to handle events with HTML or DOM.

有很多方法可以使用 HTML 或 DOM 处理事件。

Defining it in HTML

在 HTML 中定义它

<button type="button" id="hello" onclick="hello();">Click Me!</button> 

Using JQuery

使用 JQuery

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

Attaching a function to the event handler using Javascript:

使用 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");
}

Useful links

有用的链接

MDN - onclick event

MDN - onclick 事件

SO - Ans 1

SO - 答案 1

SO - Ans 2

SO - 答案 2

回答by 3pic

Pure javascript:

纯javascript:

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

Jquery:

查询:

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