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

如何用this获取菜单项索引?点击时控制台返回undefined问题求助

Solution to Log Menu Item Index on Click

Got it, let's fix this issue step by step. The problem with your current code is that this.menuImage returns undefined—this here refers to the clicked <a> element, which doesn't have a menuImage property attached to it. Plus, document.querySelectorAll() returns a NodeList, not an array, so we need to convert it first to use array methods like indexOf().

Modified HTML

We don't need to change much here—just keep the onclick handler as is (since this will automatically reference the clicked <a> element in the function):

<ul class="menuList">
 <li><a class="menuImage" onclick="openMenuItemAll();"><button>&#8250;</button>Chicken Cordon Bleu</a></li>
 <li><a class="menuImage" onclick="openMenuItemAll();"><button>&#8250;</button>Chicken Stir Fry</a></li>
 <li><a class="menuImage" onclick="openMenuItemAll();"><button>&#8250;</button>Chicken Thighs</a></li>
 <li><a class="menuImage" onclick="openMenuItemAll();"><button>&#8250;</button>Fish Fillet</a></li>
 <li><a class="menuImage" onclick="openMenuItemAll();"><button>&#8250;</button>Lasagna</a></li>
 <li><a class="menuImage" onclick="openMenuItemAll();"><button>&#8250;</button>Pizza</a></li>
 <li><a class="menuImage" onclick="openMenuItemAll();"><button>&#8250;</button>Salmon</a></li>
 <li><a class="menuImage" onclick="openMenuItemAll();"><button>&#8250;</button>Spaghetti</a></li>
</ul>

Updated JavaScript

This single function will handle all clicks, log the correct index, and uses this as requested:

function openMenuItemAll(){
  // Convert NodeList to array so we can use indexOf
  const menuItems = Array.from(document.querySelectorAll(".menuImage"));
  // Find the index of the clicked element (this) in the array
  const itemIndex = menuItems.indexOf(this);
  console.log(itemIndex);
}

How It Works:

  1. Array.from(document.querySelectorAll(".menuImage")): Converts the NodeList returned by querySelectorAll into a proper array. This lets us use array methods like indexOf().
  2. this: In the context of the onclick handler, this refers directly to the <a> element that was clicked.
  3. menuItems.indexOf(this): Finds the position of the clicked element in the array of menu items, giving us the 0-based index you want (first item = 0, second = 1, etc.).

If you prefer, you can also use the spread operator instead of Array.from() to convert the NodeList:

const menuItems = [...document.querySelectorAll(".menuImage")];

Either way, this solution sticks to your requirements: one function, no pre-defined global variables, and uses this to reference the clicked element.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:36:18