如何根据输入值获取JSON对象索引?JS技术问题求助
Let's break down why your current approach isn't working and fix this properly.
Why Your jQuery index() Method Fails
The way you're using jQuery(json.Math[val]).index({"id": inputvalue }) is incorrect for two key reasons:
- You're wrapping a single array item (
json.Math[val]) into a jQuery object, not the fullMatharray. - jQuery's
index()is designed for DOM element positioning or finding elements within a jQuery collection—it doesn't work for matching object properties in a plain JavaScript array. That's why it returns-1every time.
Step 1: Correctly Find the Index by ID
We'll use native JavaScript's findIndex() method (clean and widely supported) to locate the question with the matching id value. We'll also store the current question index globally so we can navigate to the next question easily.
First, adjust your code to store the loaded JSON data and track the current index:
let currentQuestionIndex = -1; let questionData = null; // Load JSON data once on page load $.getJSON("question.json", function(response) { questionData = response; // Optional: Initialize with the first question if needed // currentQuestionIndex = 0; // populate(questionData.Math[currentQuestionIndex]); });
Step 2: Handle Search Button Click
Update your search button click handler to find the correct index and load the question:
$("#idnumber").on('click', function(event) { event.preventDefault(); // Prevent form submission (your button is type="submit") const inputId = $("#searchid").val().trim(); // Guard clause: Ensure data is loaded if (!questionData) { alert("Question data is still loading—please wait!"); return; } // Find index of the question with matching ID (strict equality check) currentQuestionIndex = questionData.Math.findIndex(item => item.id === inputId); if (currentQuestionIndex === -1) { alert("No question found with that ID!"); return; } // Load the matching question populate(questionData.Math[currentQuestionIndex]); });
Step 3: Add "Next Question" Functionality
Assuming you have a button with ID next-question (adjust the selector to match your HTML), add this handler to navigate to the next question:
$("#next-question").on('click', function() { if (!questionData || currentQuestionIndex === -1) { alert("Please search for a question first to start navigating!"); return; } const nextIndex = currentQuestionIndex + 1; // Check if we've reached the end of the question list if (nextIndex >= questionData.Math.length) { alert("You've reached the last question!"); return; } currentQuestionIndex = nextIndex; populate(questionData.Math[currentQuestionIndex]); });
Alternative: jQuery-only Approach (If You Prefer)
If you want to stick with jQuery methods, use $.grep to filter the matching question, then get its index:
$("#idnumber").on('click', function(event) { event.preventDefault(); const inputId = $("#searchid").val().trim(); if (!questionData) { alert("Data not loaded yet!"); return; } const matchedQuestion = $.grep(questionData.Math, function(item) { return item.id === inputId; })[0]; if (!matchedQuestion) { alert("Question not found!"); return; } currentQuestionIndex = questionData.Math.indexOf(matchedQuestion); populate(matchedQuestion); });
Key Notes to Avoid Issues
- Strict Equality: Always use
===to compare the input ID with the JSONid(both are strings, so this ensures no type mismatch bugs). - Prevent Default Behavior: Your button is
type="submit", so addingevent.preventDefault()stops the page from reloading when clicked. - Data Loading Check: Never assume the JSON data is loaded immediately—add guards to handle cases where the user clicks before the data is ready.
内容的提问来源于stack exchange,提问作者Piotr

