jQuery.click() 与 onClick
htmlweb developmentfront end technology更新于 2024/7/19 10:20:17
在本文中,我们将了解 jQuery.click() 和 onClick 之间的区别。首先,让我们了解 jQuery 中的 click() 和 onClick() 是什么。
jQuery click()
示例
click() 方法会触发每个匹配元素的 click 事件。让我们看一个例子 -
<html>
<head>
<title>The jQuery click() Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script language = "javascript">
$(document).ready(function() {
$("#clickButton1").click(function(){
alert("click event occurred");
});
});
function clickFirstButton(){
$("#clickButton1").click();
}
</script>
</head>
<body>
<form name = "sampleForm">
<label>Enter Name: </label><input type = "text" id = "result1" title="Enter Name" value = "" ></input><br/><br/>
<input type = "button" id = "clickButton1" value = "Click Me!" /> <input type = "button" id = "clickButton2" value = "Click First Button!" onclick="clickFirstButton();" />
</form>
</body>
</html>
输出
点击点击我按钮 &mius;
点击点击第一个按钮按钮 −
onClick
当用户点击鼠标左键时,会触发 onclick() 事件类型。您可以针对此事件类型添加验证、警告等功能。
示例
来看一个例子 −
<!DOCTYPE html>
<html>
<head>
<script>
function myAttrFunc() {
var a = document.getElementsByTagName("a")[0].getAttribute("href");
document.getElementById("Demo").innerHTML = a;
}
</script>
</head>
<body>
<h1>Courses</h1>
<a href="https://www.cainiaomax.com/market/index.asp">Tutorialspoint Courses</a>
<p>Clicking the below button to get the above link:</p>
<button onclick="myAttrFunc()">GET THE LINK</button>
<p id="Demo"></p>
</body>
</html>
输出
点击获取链接按钮即可显示链接 -
使用 click() 更佳,因为它遵循标准事件注册模型。您可以将多个处理程序附加到同一个元素。您可以轻松访问事件对象,并且处理程序可以存在于任何函数的作用域中。此外,它是动态的,即它可以随时调用,尤其适用于动态生成的元素。无论您使用 jQuery、其他库还是直接使用原生方法,都无关紧要。
相关文章
有用资源
html 参考教程 - 该教程包含有关 html 的更多信息:https://www.cainiaomax.com/html/

