How to use jquery $(this) with $(document).keyup - Stack Overflow

admin2025-05-01  1

I have this code:

$(document).keyup( function(e) {
  console.log($(this).attr('id'));
});

When typing in an HTML input tag with an id, the output in console.log is:

undefined

How then to use $(this) within the keyup function?

I have this code:

$(document).keyup( function(e) {
  console.log($(this).attr('id'));
});

When typing in an HTML input tag with an id, the output in console.log is:

undefined

How then to use $(this) within the keyup function?

Share Improve this question asked Jan 2 at 16:46 CymroCymro 1,4742 gold badges12 silver badges35 bronze badges 2
  • 1 What are you expecting "this" to be? If you are expecting the element where the keyup event happened, you need to use the event's target. Also, consider moving away from the deprecated "keyup()" and use .on("keyup", event => {}) – Austin Duling Commented Jan 2 at 16:55
  • this is the element the event is assigned to - in your case that's document – fdomn-m Commented Jan 2 at 20:30
Add a comment  | 

1 Answer 1

Reset to default 4

The event object has a target property which can be used for this:

$(document).keyup( function(e) {
  console.log($(e.target).attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<input type="text" id="foo">


You could even take it a step further and migrate away from .keyup() and instead standardize on .on(), which can be more clear about event delegation. For example:

$(document).on('keyup', 'input', function(e) {
  console.log($(this).attr('id'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<input type="text" id="foo">

In the above case the second argument to .on() is a selector to be used at runtime to determine if the originating element should trigger the event handler, and within the event handler this refers to that originating element.

转载请注明原文地址:http://www.anycun.com/QandA/1746106652a91763.html