[英]Add event handler to HTML element using javascript
我希望在任何用戶點擊它時為段落添加事件處理程序。 例如,我有一個段落,當用戶點擊它時會顯示警告,但不在HTML上使用“onclick”。
<p id="p1">This is paragraph Click here..</p>
<a href="http://www.google.com" id="link1" >test</a>
document.getElementById('p1').onmouseover = paragraphHTML;
您可以添加事件偵聽器。
水木清華。 像這樣:
var el = document.getElementById("p1");
if (el.addEventListener) {
el.addEventListener("click", yourFunction, false);
} else {
el.attachEvent('onclick', yourFunction);
}
(感謝@Reorx)
完整代碼(在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>
為了適應大多數情況,您可以編寫一個函數來處理:
var bindEvent = function(element, type, handler) {
if (element.addEventListener) {
element.addEventListener(type, handler, false);
} else {
element.attachEvent('on'+type, handler);
}
}
將tabIndex
屬性添加到p
元素,然后可以使用onfocus
函數。
演示: http : //jsfiddle.net/9y7CL/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.