简体   繁体   中英

.keypress on a DIV tag?

Is there a way to get work .keypress on a div element like this?:

<html>
<body>

<script type="text/javascript">
<!--

$('#idtext').keypress(function(event) {
  var keyCode = event.keyCode;
  $('#idtext').text(function(i, text) {

   return text + String.fromCharCode(keyCode); 

  });

});

// -->
</script>

<div id="idtext"></div>

</body>
</html>

Yes: you need to add a tabindex attribute to the <div> to allow it to receive the focus.

<div id="idtext" tabindex="1"></div>

Also, the property you want for the character code of the text entered in a keypress event is which , not keyCode .

Finally, the HTML comment tags inside the <script> element are unnecessary in all modern browsers.

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