点击.item元素时,如何通过类名提取ID值?
Solution to Extract ID from Class Name
Great question! Since you've already got the click event set up for .item elements, here's a straightforward way to pull that numeric ID from the item-id-XXX class using match():
Inside your click handler:
$(document).on('click', '.item', function() { // Get all classes of the clicked element as a string const classList = this.className; // Use regex to target "item-id-" followed by digits, capturing the numeric part const idMatch = classList.match(/item-id-(\d+)/); // Extract the ID only if a match is found if (idMatch) { const itemId = idMatch[1]; // This will be "123" (string format) // Convert to number if needed: const itemIdNum = parseInt(itemId, 10); // Use the ID however you need here console.log('Extracted ID:', itemId); } });
Key Breakdown:
- The regex
/item-id-(\d+)/specifically looks for the substringitem-id-followed by one or more digits (\d+). The parentheses()create a capture group that isolates just the numeric ID. - If a match is found,
idMatchbecomes an array: the first element is the full matched string (item-id-123), and the second element is the captured digits (123). - We add a check for
idMatchto avoid errors in case the class is missing (though your setup suggests it will always be present).
Modern JS Shortcut (Optional Chaining):
If you're working with ES2020 or later, you can simplify this with optional chaining to handle edge cases cleanly:
$(document).on('click', '.item', function() { const itemId = this.className.match(/item-id-(\d+)/)?.[1]; if (itemId) { // Proceed with the ID } });
This approach is reliable even if the element has multiple classes (like your .item and .item-id-123 combo) because the regex will target the exact class pattern you need.
内容的提问来源于stack exchange,提问作者Henrik Petterson
相关产品推荐
相关产品推荐

