开发者

How to add on key down and on key up event in java script

I am creating an live search for my blog..i got this from w3 schools and i need to add on keyboard up,down mouse up and down event ...

<html>
<head>
<script type="text/javascript">
function showResult(str)
{
if (str.length==0)
  {
 开发者_运维问答 document.getElementById("livesearch").innerHTML="";
  document.getElementById("livesearch").style.border="0px";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
    document.getElementById("livesearch").style.border="1px solid #A5ACB2";
    }
  }
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<input type="text" size="30" onkeyup="showResult(this.value)" />
<div id="livesearch"></div>
</form>

</body>
</html> 


Just add it into the element:

<input onkeyup="showResult(this.value)" onkeydown="showResult(this.value)" type="text" size="30" />


I use <input type="text" onkeypress="doThings();" onkeydown="doThings();"/>

For handling mouse use onmousedown and onmouseup events.


Learn using a Javascript library (such as jQuery). Handling events manually is a pain, because half the code you will have to write will be compatibility wrappers for various browser inconsistencies. Adding a keydown handler to an element with id foo in jQuery is as simple as

$('#foo').keydown(function() {
  // do stuff
});

Edit: The same is true for AJAX. The code you pasted in the question would look something like this in jQuery:

function showResult(str) {
  if (str.length==0) {
    $('#livesearch').html('').css('border', 0);
    return;
  }
  $.get('livesearch.php', {q: str}, function(data) {
    $('#livesearch').html(data).css('border', '1px solid #A5ACB2');
  });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜