输入框内文本点击功能实现失败,寻求技术解决方案
问题描述
我正在自主开发一款词汇学习页面,该页面可在输入句子的难词旁添加括号包裹的释义,帮助结合语境学习词汇。目前已实现多项功能,最后需添加的功能为:让输入框内的难词可点击,并自动填入下一个输入框,无需手动输入。但我编写的代码无法实现该功能,以下是我的代码:
HTML 代码
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <div align="center"> <h1>Meaning In Sentence</h1> <div> <h3>Sentence:</h3> <input type="text" id="sentence" class="form-control" style="width:80%" placeholder="Enter the sentence containing difficult words" autofocus> </div> <br> <h3>Difficult Words and Meanings:</h3> <textarea id="wordMeanings" class="form-control" style="width:80%" placeholder="Enter difficult words and their meanings (one word-meaning pair per line, separated by ':'). For multiple meanings, separate them by commas. Example: word1: meaning1, meaning2 word2: meaning3"></textarea> <br> <div align="center"> <button type="button" class="btn btn-default" onclick="modifySentence()" id="modifyButton">Modify Sentence</button> <button type="button" class="btn btn-default" onclick="copyHistoryToClipboard()">Copy History</button> <div class="copy-success" id="copySuccessMessage">Copied!</div> </div> <br> <div class="h4" align="center"> <h3>Modified Sentence:</h3> <p id="modifiedsentence"></p> </div> <div id="historySection"> <h3>History:</h3> <ul id="history"></ul> </div> </div>
CSS 代码
#one { margin-left: auto; margin-right: auto; width: 90%; } .copy-success { display: none; color: green; font-weight: bold; margin-top: 5px; } /* Style for modified sentence and history */ #modifiedsentence, #history li { font-family: Arial, sans-serif; font-size: 12pt; } /* Style for highlighted words */ .highlighted { background-color: yellow; }
JavaScript 代码
document.getElementById("sentence").focus(); function modifySentence() { const sentence = document.getElementById("sentence").value.trim(); const wordMeaningsInput = document.getElementById("wordMeanings").value.trim(); if (!sentence || !wordMeaningsInput) { alert("Please enter both a sentence and word-meaning pairs."); return; } const wordMeanings = {}; const lines = wordMeaningsInput.split('\n'); for (const line of lines) { const [word, meaningsStr] = line.split(':').map(s => s.trim()); if (word && meaningsStr) { wordMeanings[word] = meaningsStr.split(',').map(s => s.trim()); } } let modifiedSentence = sentence; for (const word in wordMeanings) { const meanings = wordMeanings[word]; const replacement = `<b>${word} (${meanings.join(', ')})</b>`; modifiedSentence = modifiedSentence.replace(new RegExp(`\\b${word}\\b`, 'gi'), replacement); } document.getElementById("modifiedsentence").innerHTML = modifiedSentence; const formattedSentence = document.getElementById("modifiedsentence").innerHTML; addToHistory(formattedSentence); document.getElementById("sentence").value = ""; document.getElementById("wordMeanings").value = ""; } function addToHistory(sentence) { const historyList = document.getElementById("history"); const listItem = document.createElement("li"); listItem.innerHTML = sentence; historyList.appendChild(listItem); } function copyHistoryToClipboard() { const historyList = document.getElementById("history"); const range = document.createRange(); range.selectNodeContents(historyList); window.getSelection().removeAllRanges(); window.getSelection().addRange(range); document.execCommand("copy"); window.getSelection().removeAllRanges(); const copySuccessMessage = document.getElementById("copySuccessMessage"); copySuccessMessage.style.display = "block"; setTimeout(() => { copySuccessMessage.style.display = "none"; }, 1500); } document.addEventListener('keydown', function(event) { if (event.ctrlKey && event.key === 'Enter') { modifySentence(); } }); document.getElementById("modifiedsentence").addEventListener("click", function() { document.getElementById("sentence").focus(); }); function handleWordClick(clickedWord) { const wordMeaningsTextArea = document.getElementById("wordMeanings"); const existingText = wordMeaningsTextArea.value; if (!existingText.includes(clickedWord + ":")) { wordMeaningsTextArea.value += (existingText ? "\n" : "") + clickedWord + ": "; // Highlight the clicked word WITHOUT re-wrapping all words: const sentenceInput = document.getElementById("sentence"); const wordElements = sentenceInput.querySelectorAll('span'); // Get all existing spans wordElements.forEach(wordElement => { if (wordElement.textContent === clickedWord && !wordElement.classList.contains('highlighted')) { wordElement.classList.add('highlighted'); } }); wordMeaningsTextArea.focus(); } } function wrapWordsInSpans(sentenceInputId) { const sentenceInput = document.getElementById(sentenceInputId); const sentenceText = sentenceInput.value; const words = sentenceText.split(/\s+/); // Create a temporary element to hold the wrapped words const tempSpan = document.createElement('span'); tempSpan.innerHTML = words.map(word => { // Check if the word is already highlighted const isHighlighted = sentenceInput.querySelector(`span.highlighted:contains("${word}")`); // Wrap with or without the highlighted class return isHighlighted ? `<span class="highlighted" onclick="handleWordClick('${word}')">${word}</span>` : `<span onclick="handleWordClick('${word}')">${word}</span>`; }).join(" "); // Replace the content of the input with the wrapped words sentenceInput.innerHTML = tempSpan.innerHTML; } document.getElementById("sentence").addEventListener("input", function() { wrapWordsInSpans("sentence"); });
内容的提问来源于stack exchange,提问作者yaseen wazir
相关产品推荐
相关产品推荐

