如何在选择器字段中获取ID?能否将输入框ID传入选择器字段?
Absolutely! You can target an input element by its ID directly in your selector, and dynamically access that ID when interacting with the element. Let’s break this down, fix the syntax issues in your code, and show you how to achieve what you’re aiming for.
First, let’s address the syntax errors in your original code:
$(':input'.get(0))is invalid—you need to call.get(0)on the jQuery object, not the string selector. It should be$(':input').get(0)(to get the first input as a DOM element) or just$(':input').first()if you want a jQuery object.Object.values($write)doesn’t make sense here: if$writeis a DOM element or jQuery object, this won’t produce a string you can split with":".
Example 1: Target a Specific Input by ID
If you already know the ID of the input you want to target, you can directly include it in the selector:
// Target the input with ID "my-input" const $write = $('#my-input'); $write.on('click', function() { const inputId = this.id; // This will be "my-input" let shift = false; let capslock = false; console.log(`Clicked input ID: ${inputId}`); });
Example 2: Dynamically Get ID of Any Clicked Input
If you want to handle clicks on any input and retrieve its ID dynamically (without hardcoding the selector), do this:
// Attach click handler to all input elements $(':input').on('click', function() { const inputId = this.id; // Gets the ID of the specific input that was clicked let shift = false; let capslock = false; // If you need to work with the clicked input as a jQuery object: const $clickedInput = $(this); console.log(`Input ID: ${inputId}`); });
Example 3: Pass an ID Into the Selector Dynamically
If you have an ID stored in a variable and want to use it to target an input, you can use template literals to insert it into the selector string:
// Suppose this ID comes from somewhere else (like a variable) const targetId = 'email-input'; // Use the variable to build the selector const $write = $(`#${targetId}`); $write.on('click', function() { console.log(`Targeted input ID: ${this.id}`); // Logs "email-input" });
All these approaches let you work with the input’s ID either directly in the selector or dynamically when the element is interacted with.
内容的提问来源于stack exchange,提问作者Vivek Pandey

