使用javascript将事件处理程序添加到HTML元素 [英] Add event handler to HTML element using javascript
本文介绍了使用javascript将事件处理程序添加到HTML元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望在任何用户点击它时为段落添加事件处理程序。例如,我有一个段落,当用户点击它时会显示警告,但不在HTML上使用onclick。
I want to add an event handler to a paragraph for when any user clicks on it. For example, I have a paragraph which would show an alert when a user clicks it, but without using "onclick" on HTML.
<p id="p1">This is paragraph Click here..</p>
<a href="http://www.google.com" id="link1" >test</a>
document.getElementById('p1').onmouseover = paragraphHTML;
推荐答案
您可以添加事件监听器。
Smth。像这样:
You can add event listener.
Smth. like this:
var el = document.getElementById("p1");
if (el.addEventListener) {
el.addEventListener("click", yourFunction, false);
} else {
el.attachEvent('onclick', yourFunction);
}
(谢谢@Reorx)
完整代码(在Chrome和IE7中测试):
Complete code (tested in Chrome&IE7):
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1255">
<script type="text/javascript">
window.onload =function (){
var el = document.getElementById("p1");
if (el.addEventListener) {
el.addEventListener("click", yourFunction, false);
} else {
el.attachEvent('onclick', yourFunction);
}
};
function yourFunction(){
alert("test");
}
</script>
</head>
<body>
<p id="p1">test</p>
</body>
</html>
这篇关于使用javascript将事件处理程序添加到HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文