如何用this获取菜单项索引?点击时控制台返回undefined问题求助
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>›</button>Chicken Cordon Bleu</a></li> <li><a class="menuImage" onclick="openMenuItemAll();"><button>›</button>Chicken Stir Fry</a></li> <li><a class="menuImage" onclick="openMenuItemAll();"><button>›</button>Chicken Thighs</a></li> <li><a class="menuImage" onclick="openMenuItemAll();"><button>›</button>Fish Fillet</a></li> <li><a class="menuImage" onclick="openMenuItemAll();"><button>›</button>Lasagna</a></li> <li><a class="menuImage" onclick="openMenuItemAll();"><button>›</button>Pizza</a></li> <li><a class="menuImage" onclick="openMenuItemAll();"><button>›</button>Salmon</a></li> <li><a class="menuImage" onclick="openMenuItemAll();"><button>›</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:
Array.from(document.querySelectorAll(".menuImage")): Converts the NodeList returned byquerySelectorAllinto a proper array. This lets us use array methods likeindexOf().this: In the context of the onclick handler,thisrefers directly to the<a>element that was clicked.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

