为 HTML 中的特定 id 调用 JS 函数
Call JS function for specific id in HTML
我在 js 文件夹中的 JS 文件名中有以下函数 hello.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>
<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>
如何将 hello()
功能附加到带有 id="hello"
的按钮?我做错了什么,但我找不到什么。
编辑: 为了完整起见,我建议阅读所有答案。
Edit2: 这个问题的目的是阐明在 html 上将函数附加到特定元素的一般方法。按钮和点击交互就是一个例子。
使用.on()
绑定事件处理器。
$("#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
<button type="button" id="hello" onclick="hello();">Click Me!</button>
使用JQuery
$("#hello").click(hello);
使用 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");
}
有用的链接
SO - Ans 1
SO - Ans 2
我在 js 文件夹中的 JS 文件名中有以下函数 hello.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>
<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>
如何将 hello()
功能附加到带有 id="hello"
的按钮?我做错了什么,但我找不到什么。
编辑: 为了完整起见,我建议阅读所有答案。
Edit2: 这个问题的目的是阐明在 html 上将函数附加到特定元素的一般方法。按钮和点击交互就是一个例子。
使用.on()
绑定事件处理器。
$("#hello").on('click', hello);
您可能希望使用 hello
作为处理程序
hello
的按钮上绑定 click
事件
$("#hello").click(hello);
纯javascript:
var elm=document.getElementById("hello");
elm.onclick= function{ hello();};
Jquery:
$("#hello").click(hello() );
使用HTML或DOM有很多方法可以处理事件。
定义在HTML
<button type="button" id="hello" onclick="hello();">Click Me!</button>
使用JQuery
$("#hello").click(hello);
使用 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");
}
有用的链接
SO - Ans 1
SO - Ans 2