You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击.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 substring item-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, idMatch becomes 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 idMatch to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:44:14