日期:2014-05-17 浏览次数:21087 次
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Simulate Event</title>
<script type="text/javascript">
function simulateKeyEvent(target, keyCode) {
if (!target) {
alert("Target is not exist");
}
var customEvent = null;
var a = typeof document.createEvent;
if (typeof document.createEvent == "function") {
try { //firefox
customEvent = document.createEvent("KeyEvents");
customEvent.initKeyEvent("keypress", true, true, window, false, false, false, false, keyCode, keyCode);
} catch(ex) {
document.write("Shit happends. This example is only demonstrating event simulation in firefox and IE.");
}
target.dispatchEvent(customEvent);
} else if (document.createEventObject) { //IE
customEvent = document.createEventObject();
customEvent.bubbles = true;
customEvent.cancelable = true;
customEvent.view = window;
customEvent.ctrlKey = false;
customEvent.altKey = false;
customEvent.shiftKey = false;
customEvent.metaKey = false;
customEvent.keyCode = keyCode;
target.fireEvent("onkeypress", customEvent);
} else {
document.write("This example is only demonstrating event simulation in firefox and IE.");
}
}
</script>
</head>
<body>
<input id="testinput" type="button" value="kick you"/>
</body>
<script type="text/javascript">
var target = document.getElementById("testinput");
target.onkeypress = function(event) {
var event = (event) ? event: window.event;
if (event.keyCode == 27) {
alert('"ESC" pressed');
}
};
simulateKeyEvent(target, 27);
</script>
</html>
------解决方案--------------------
通过设置一个全局标记变量,再配合后台处理一下就很容易解决了。
你的请求发出后,要等待服务器的处理和返回,在返回的时候才设置显示。你要取消的时机就在于返回之前。
每个按钮的点击事件都是同一个方法,参数不同。则在该方法里把参数赋给一个变量(假设名为“当前值”),它代表了当前所按的按钮。在发起AJAX请求时,将这个参数随同传递给后台。后台在处理完之后,将结果和这个参数一同返回,形式可以用“参数值|结果”这类的(根据你的情况自己决定)。
这样返回来的结果里就带了你上次请求时是哪个按钮发出去的信息了。在要设置显示的时候,把结果里的“参数值”取出来,跟变量“当前值”比较一下看是否相等,不等就不设置。
这样的话,你按了A,不按B的情况下,参数A和当前值A相等,正常设置显示。
如果按了A发出请求后,又按了B,则此时当前值变成B,而当A请求返回后发现参数A和当前值B不等,就不设置,等B请求返回后,相等,设置。