onkeydown触发后,是不是不会再触发onkeypress?

glovej 2012-01-19 09:41:46
我写了个代码,来检测三种事件的触发情况,结果发现keypress对应的文本框t2不会有任何内容

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type=text/javascript src="./jquery.js"></script>
<script>
function f()
{


}


function g(this_text,ev)
{

this_text.value = ev.keyCode;
ev.keyCode = 0;
ev.returnValue = false;
return false;

}
function g1(ev)
{

t2.value = ev.keyCode;
ev.keyCode=0;
ev.returnValue=false;
return false;
}

function g2(ev)
{
t3.value=ev.keyCode;
ev.keyCode=0;
ev.returnValue =false;
return false;
}
</script>

</head>
<body onload="f();">
<input type=text id=t1 onkeydown="g(this,event);" onkeypress="g1(event);" onkeyup="g2(event);">
<input type=text id=t2>
<input type=text id=t3>

</body>
</html>


...全文
121 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
风一样的大叔 2012-01-20
  • 打赏
  • 举报
回复
看帖留名,学习无罪
p2227 2012-01-19
  • 打赏
  • 举报
回复
前后依次发生的两个事件,前一个return false(也有一些浏览器是用ev.returnValue=false;)的话,后一个就不再执行了
本帖相关的三个事件发生次序是keydown keypress keyup


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>

</head>
<body>
<input type=text id=t1 onkeydown="g(event);" onkeypress="g1(event);" onkeyup="g2(event);">
<textarea id="r" rows="20" cols="40" ></textarea>
<script>

var t2 = document.getElementById("r");
function g(event)
{
event = event || window.event;
t2.value += "onkeydown,keyCode = " + event.keyCode + "\n"


}
function g1(event)
{
event = event || window.event;
t2.value += "onkeypress,keyCode = " + event.keyCode + "\n"

}

function g2(event)
{
event = event || window.event;
t2.value += "onkeyup,keyCode = " + event.keyCode + "\n"
}
</script>

</body>
</html>
wdbjsh 2012-01-19
  • 打赏
  • 举报
回复
onkeydown return 之后,本次的keydown事件就被系统忽略了

而keypress事件是 keydown+keyup 算一次有效keydown

你把keydown忽略了,自然keypress就不成立了
glovej 2012-01-19
  • 打赏
  • 举报
回复
果然是删了就有了啊,不过删ev.keyCode没有效果,删returnvalue才有效果,请问何解啊,为什么不同的事件还会相互有影响的,不是说事件顺序是down,press,up的吗
p2227 2012-01-19
  • 打赏
  • 举报
回复
ev.keyCode=0;
ev.returnValue=false;
return false;

把这些都删掉
glovej 2012-01-19
  • 打赏
  • 举报
回复
浏览器IE8

87,990

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧