button添加的事件可以触发,但input type=button的事件无效,为什么?<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>1</title>
<script language="javascript" src="jquery-1.4.2.min.js"></script>
<script language="javascript">
function start(){
var e=document.activeElement;
if(e.id=="1"){
$("div").text("aaa");
}
if(e.id=="2"){
$("div").text("bbb");
}
}
</script>
</head><body>
<button onclick="start()" id="1">提交</button>
<input type="button" value="提交" onclick="start()" id="2">
<br>
<div id="target"></div>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>1</title>
<script language="javascript" src="jquery-1.4.2.min.js"></script>
<script language="javascript">
function start(){
var e=document.activeElement;
if(e.id=="1"){
$("div").text("aaa");
}
if(e.id=="2"){
$("div").text("bbb");
}
}
</script>
</head><body>
<button onclick="start()" id="1">提交</button>
<input type="button" value="提交" onclick="start()" id="2">
<br>
<div id="target"></div>
</body>
</html>
试试动态添加事件<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>1</title> <script language="javascript" src="jquery-1.4.2.min.js"></script> <script language="javascript">
function start() {
document.getElementsByTagName("input")[0].onclick = function() {
document.getElementById("div").innerHTML = "bbb";
}
var e = document.activeElement;
if (e.id == "1") {
document.getElementById("div").innerHTML = "aaa";
}
if (e.id == "2") {
document.getElementById("div").innerHTML = "bbb";
}
}
</script></head>
<body>
<button onclick="start()" id="1">
提交</button>
<input type="button" value="提交" id="2" />
<br />
<div id="div">
</div>
</body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>1</title>
</head><body>
<button onclick="ShowTip()" id="1">提交</button>
<input type="button" value="提交" onclick="ShowTip()" id="2" />
<br />
<div id="target"></div>
</body>
<script language="javascript" defer>
function $(id) {
return document.getElementById(id);
}
$("target").text = function(message) {
this.innerHTML = message;
};
// start 函数名与 input 的 start 属性重名,因此报错!
function ShowTip(){
var e=document.activeElement ? document.activeElement : event.srcElement;
if(e.id=="1"){
$("target").text("aaa");
}
if(e.id=="2"){
$("target").text("bbb");
}
}
</script>
</html>