JavaScript:点击前后按钮处于数组首尾时弹出提示框的需求及代码调整
Got it, let's fix up your code to show alert prompts when users try to navigate beyond the first or last item in your person array. Here's how to implement it smoothly:
Updated Full Code
// Make sure these are defined in your scope (adjust as needed) // const person = [ // { fname: "John", lname: "Doe", age: 30, salary: 50000 }, // { fname: "Jane", lname: "Smith", age: 28, salary: 55000 }, // // Add more items here // ]; // let arr = 0; // Starting index function myFunction() { document.getElementById("f").value = person[arr].fname; document.getElementById("l").value = person[arr].lname; document.getElementById("a").value = person[arr].age; document.getElementById("s").value = person[arr].salary; } // Attach click listeners document.getElementById("prevbtn").addEventListener("click", myFunctionPrev); document.getElementById("nxtbtn").addEventListener("click", myFunctionNext); function myFunctionPrev() { if (arr > 0) { arr -= 1; myFunction(); // Update the UI with the previous item } else { // Alert when user tries to go before the first item alert("You're already on the first entry!"); } } function myFunctionNext() { // Use person.length - 1 instead of hardcoded 3 for flexibility if (arr < person.length - 1) { arr += 1; myFunction(); // Update the UI with the next item } else { // Alert when user tries to go past the last item alert("You've reached the last entry!"); } }
What Changed & Why
- Previous Button Logic: We added an
elseclause that triggers an alert whenarris already at 0 (the first index). Now users get clear feedback instead of nothing happening when they click "Previous" on the first item. - Next Button Logic: Replaced the hardcoded
3withperson.length - 1—this makes your code dynamic. If you add or remove entries from thepersonarray later, you won't have to manually update this number. Theelseblock here alerts users when they can't go further than the last entry.
This small tweak makes your navigation much more user-friendly by communicating boundaries clearly!
内容的提问来源于stack exchange,提问作者Fadhel
相关产品推荐
相关产品推荐

