为何我的JavaScript函数无法获取input框的value作为参数?
Hey there! Let's break down what's going wrong with your code and fix it up quickly.
First, the core issues:
Incorrect event listener callback setup
You're currently callingdisplayParaOutput(para1.value, para2.value)directly when attaching the event listener. This means the function runs immediately when the page loads (not when you click the button), and it uses the initial empty values of your inputs—so clicking the button later does nothing.Console reference error
TheUncaught ReferenceError: para1value is not definedhappens becausepara1valueis a local parameter inside yourdisplayParaOutputfunction. It only exists within that function's scope, so you can't access it directly from the global console.
Here are two straightforward fixes:
Fix 1: Use an anonymous wrapper function
This lets you pass the current input values only when the button is clicked:
let para1 = document.getElementById("para1"); let para2 = document.getElementById("para2"); let btnFunctionPara = document.getElementById("btnFunctionPara"); let para1Output = document.getElementById("para1Output"); let para2Output = document.getElementById("para2Output"); // Wrap the function call in an anonymous function to delay execution until click btnFunctionPara.addEventListener("click", function() { displayParaOutput(para1.value, para2.value); }); function displayParaOutput(para1value, para2value) { para1Output.innerHTML = para1value; para2Output.innerHTML = para2value; // If you want to debug, log values here (inside the function scope) console.log(para1value, para2value); }
Fix 2: Simplify by getting values inside the function
Even cleaner—let the function fetch the latest input values itself when triggered:
let para1 = document.getElementById("para1"); let para2 = document.getElementById("para2"); let btnFunctionPara = document.getElementById("btnFunctionPara"); let para1Output = document.getElementById("para1Output"); let para2Output = document.getElementById("para2Output"); // Pass the function itself (no parentheses!) to run on click btnFunctionPara.addEventListener("click", displayParaOutput); function displayParaOutput() { // Grab current values when the button is clicked const para1Value = para1.value; const para2Value = para2.value; para1Output.innerHTML = para1Value; para2Output.innerHTML = para2Value; console.log(para1Value, para2Value); // Debug here if needed }
Why this works:
When you use addEventListener, the second argument needs to be a function reference (not a function call with parentheses). If you add parentheses, JavaScript executes the function right away and uses its return value (which is undefined here) as the callback—hence why your original code didn't work on click.
To debug the values, add console.log inside the displayParaOutput function (not in the global console) since that's where the variables exist.
内容的提问来源于stack exchange,提问作者tedtyrone

