无需jQuery及ID/类选择器,如何通过input标签获取输入值?
Equivalent Vanilla JavaScript Solution
No problem! You can replicate your jQuery delegated event behavior using plain JavaScript without relying on getElementById, class selectors, or any libraries. Here's the exact equivalent code:
document.addEventListener('keyup', function(e) { // Verify the event came from an <input> element if (e.target.tagName === 'INPUT') { console.log(e.target.value); } });
Breakdown of how this works:
- We attach the
keyuplistener to thedocument(mirroring your jQuery$(document).on(...)approach) to handle events from all inputs, even those added dynamically later. - When a keyup event bubbles up to the document, we check if the original triggering element (
e.target) is an input. DOM tag names are always uppercase, so we compare against'INPUT'. - Once confirmed, we grab the input's value directly with
e.target.value—simple and straightforward, no extra selectors needed.
This will behave exactly like your jQuery code, logging the value of any input whenever a key is released.
内容的提问来源于stack exchange,提问作者RedoColor
相关产品推荐
相关产品推荐

