我想用按键删除php会话变量。所以我用了这些代码,
<script type="text/javascript">
function textsizer(e){
var evtobj=window.event? event : e
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
var actualkey=String.fromCharCode(unicode)
if(actualkey=="x"){
location.href="biling.php?cmd="+actualkey;}
}
document.onkeypress=textsizer
</script>
<?php if(isset($_GET['cmd'])){
unset($_SESSION["bill_array"]);
header('location:biling.php');
}
?> }
但问题是,当我在文本框中键入"x"时,这段代码也会清除会话。所以我只想停止它,只在我按下文本框的"x"时清除会话
我认为您可以这样编辑现有函数:
function textsizer(e) {
var evtobj=window.event? event : e;
var element = evtobj.target ? evtobj.target : evtobj.srcElement;
if (element.tagName.toLowerCase() == "body") {
var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode;
var actualkey=String.fromCharCode(unicode)
if(actualkey=="x"){
location.href="biling.php?cmd="+actualkey;
}
}
}
您可以检查e.target
属性以确定哪个元素触发keypress
事件。
//Does not work on IE
window.addEventListener('keypress', function(e){ console.log(e.target) }, false)
在e.target.tagName == 'BODY'
时采取行动是一个不错的选择。
更新
有关Event
的更多信息,请查看:
- 火狐&Webkit,https://developer.mozilla.org/en/DOM/event
- 即,http://msdn.microsoft.com/en-us/library/ie/ms535863(v=vs.85).aspx
$("input[type='text']").keypress(function(){
});