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

如何用原生JavaScript通过事件委托获取动态创建锚点的ID

解决原生JS事件委托获取动态锚点ID并传入函数的问题

问题分析

你的代码存在两个核心问题:

  1. 箭头函数没有独立的this绑定,因此this.id无法获取锚点元素的ID,需直接通过event.target访问触发事件的元素。
  2. showRecipe需要对应食谱的数据,但当前data是getRecipe内部的局部变量,点击事件触发时无法访问,需将数据存储到全局或可访问的作用域中。

修正后的代码

HTML部分(保持不变)

<button type="button" id="btn">Seach!</button>
<div id="recipeContainer"></div>

JavaScript部分

// 全局存储食谱数据,供点击事件调用
let recipeData = [];

document.querySelector('#btn').addEventListener('click', getRecipe);
document.querySelector('#recipeContainer').addEventListener('click', event => {
  // 阻止锚点默认跳转行为,避免页面滚动到顶部
  event.preventDefault();
  // 验证触发元素是否为目标锚点(支持多类名场景)
  if (event.target.classList.contains('recipeTitles')) {
    // 获取锚点ID并转为数字,匹配数据中的ID类型
    const recipeId = Number(event.target.id);
    // 根据ID找到对应的数据项
    const targetRecipe = recipeData.find(item => item.id === recipeId);
    // 调用showRecipe函数
    showRecipe(recipeId, targetRecipe);
  }
});

function getRecipe() {
  // 模拟API返回数据,实际项目替换为真实接口请求
  recipeData = [
    {
      id: 661447,
      title: "Square Deviled Eggs",
      image: "https://spoonacular.com/recipeImages/661447-312x231.jpg",
      imageType: "jpg",
      usedIngredientCount: 2
    }, 
    {
      id: 638035,
      title: "Chicken Cordon Bleu",
      image: "https://spoonacular.com/recipeImages/638035-312x231.jpg",
      imageType: "jpg",
      usedIngredientCount: 2
    }
  ];

  // 生成食谱标题HTML字符串
  const recipeTitles = recipeData.map(el => 
    `<h2><a href="#" class="recipeTitles" id="${el.id}">${el.title}</a></h2>`
  ).join('');

  document.querySelector('#recipeContainer').innerHTML = recipeTitles;
}

function showRecipe(id, data) {
  console.log(`食谱ID:${id}`);
  console.log(`完整食谱信息:`, data);
  console.log(`食谱标题:${data.title}`);
}

关键修改说明

  • 将食谱数据存入全局变量recipeData,确保点击事件触发时能获取到对应数据。
  • 用event.target.id替代this.id获取锚点ID,同时转为数字类型匹配数据中的ID格式。
  • 添加event.preventDefault()阻止锚点默认跳转行为,优化用户体验。
  • 使用classList.contains()替代直接比较className,适配元素有多个类名的场景,提升代码健壮性。

内容的提问来源于stack exchange,提问作者acodeaday

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:45:43