求助:函数触发Uncaught ReferenceError: sync is not defined错误
Hey there! Let's get that text sync issue sorted out for you. The error you're seeing (Uncaught ReferenceError: sync is not defined) is the key clue here—let's break down what's happening and how to fix it.
Why the Error Happens
The sync function you're calling from the input's onkeyup attribute isn't accessible in the global scope. This usually happens if you've defined the function inside a block (like a DOMContentLoaded wrapper) or used let/const to declare it, which limits its availability only to that local scope. The inline onkeyup handler looks for functions in the global scope, so it can't find your sync function.
Solution 1: Make the Function Globally Available
If you want to keep using the inline onkeyup handler, just define your sync function in the global scope. Here's how:
// Define the function globally so the inline handler can find it function sync() { const inputElement = document.getElementById('input'); const outputElement = document.getElementById('output'); outputElement.value = inputElement.value; }
Keep your HTML as is:
<input type="text" id="input" onkeyup="sync()"> <textarea id="output"></textarea>
Solution 2: Use addEventListener (Recommended)
Inline event handlers can get messy as your code grows, so a cleaner approach is to attach the event listener directly in JavaScript. This avoids global scope pollution and keeps your logic organized:
HTML
<input type="text" id="input"> <textarea id="output"></textarea>
JavaScript
// Wait for the DOM to fully load before accessing elements document.addEventListener('DOMContentLoaded', function() { const input = document.getElementById('input'); const output = document.getElementById('output'); // Attach the keyup event listener input.addEventListener('keyup', function() { output.value = input.value; }); });
Test It Out
Either of these methods will make your textarea mirror the input text in real-time as you type. Just refresh your page and start typing—you should see the text sync up immediately!
内容的提问来源于stack exchange,提问作者Axwell Vail

