简体   繁体   中英

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> 

只需将其添加到元素中:

<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');
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM