javascript中如何判断是否按了删除键

JavaScript09

javascript中如何判断是否按了删除键,第1张

加上键盘事件onkeydown,然后判断按下的键是不是delete键就可以了。delete键的代码是46.

例子如下:

<!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/htmlcharset=utf-8" />

<title>无标题文档</title>

</head>

<body>

<script type="text/javascript">

document.onkeydown = checkdelete

function checkdelete(e)

{

var e = window.event || e

var code = e.which || e.keyCode

if(code == 46)

{

alert("您按了删除键")

}

}

</script>

</body>

</html>

<!doctype html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Document</title>

<style>

*{margin:0padding: 0}

    #div_id p{width:80pxheight:30pxtext-align: leftborder: 1px solid #000line-height: 30px}

    #div_id p button{float:rightheight:30px}

</style>

<script src = "js/tool.js"></script>

    <script>

     window.onload = function(){

var div = document.getElementById("div_id")

     var button = document.getElementsByTagName("button")

         for(var i = 0 i < button.length - 1 i++){

          button[i].onclick = function(){

          alert("加入购物车成功")

          var p = document.createElement("p")

          var pContent = document.createTextNode(this.innerHTML)

p.appendChild(pContent)

          div.appendChild(p)

                    var delBtn = document.createElement("button")

                    var delBtnContent = document.createTextNode("x")

delBtn.appendChild(delBtnContent)

p.appendChild(delBtn)

                    delBtn.onclick = function(){

                     div.removeChild(p)

                    }

                    //setCookie("购物",div.innerHTML,getDate(100))

          }

         }

         var isTrue = false

            var button1 = document.getElementById("button_id")

            button1.onclick = function(){

             if(isTrue == false){

button1.innerHTML ="隐藏购物车"

isTrue = true

/*if(getCookie("购物") != undefined){

div.innerHTML = getCookie("购物")

}*/

div.style.display = "block"

}else if(isTrue){

button1.innerHTML ="显示购物车"

isTrue = false

div.style.display = "none"

/*if(getCookie("购物") != undefined){

div.innerHTML = getCookie("购物")

div.style.display = "none"

}*/

}

}

}

    </script>

</head>

<body>

<button>商品1</button>

<button>商品2</button>

<button>商品3</button>

<button>商品4</button>

<button>商品5</button><br/><br/>

<button id = "button_id">显示购物车</button>

<div id = "div_id" style="display:none"></div>

</body>

</html>

js没有字典这个数据类型,js的对象都是键值对的,判断对象有没有key很简单,如: var person = { name: 'zero'}// 判断person里面有没有name这个键,可以这样var key = 'name'alert(!!person[key])