如何将onclick相关文本移入文本域,及点击按钮显示下拉选中文本而非索引
Hey there! Let's break down your two questions and fix them up for you:
I'm assuming you mean either moving specific text tied to an onclick event into a textarea, or extracting the actual onclick code text from an element into the textarea. Here are solutions for both common scenarios:
场景1:点击元素时将指定文本移入文本域
If you want to insert pre-defined or element-associated text into a textarea when clicking a button/element, use this example:
<!-- 目标文本域 --> <textarea id="myTextarea" rows="4" cols="50"></textarea> <!-- 绑定点击事件的按钮 --> <button onclick="moveTextToTextarea()">点击移入文本</button> <script> function moveTextToTextarea() { // 可以替换成你需要移入的任意文本,比如其他元素的innerText const textToMove = "这是和点击事件关联的文本内容"; const textarea = document.getElementById("myTextarea"); // 覆盖文本域内容,若要追加则用 textarea.value += textToMove; textarea.value = textToMove; } </script>
场景2:提取元素的onclick属性文本到文本域
If you want to pull the actual code from an element's onclick attribute into the textarea, try this:
<textarea id="myTextarea" rows="4" cols="50"></textarea> <button id="targetBtn" onclick="extractOnclickText()">点击查看onclick代码</button> <script> function extractOnclickText() { const btn = document.getElementById("targetBtn"); // 获取按钮的onclick属性内容 const onclickCode = btn.getAttribute("onclick"); const textarea = document.getElementById("myTextarea"); textarea.value = onclickCode; } </script>
Your current code uses selectedIndex which only gives the position number of the selected option. To get the visible text instead, you just need to access the corresponding option element via that index and grab its text property. Here's the updated code:
<select id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> <input type="button" onclick="getSelectedText()" value="Display the text of the selected option"> <p id="demo"></p> <script> function getSelectedText() { const selectEl = document.getElementById("mySelect"); // 通过选中索引获取对应option的文本 const selectedText = selectEl.options[selectEl.selectedIndex].text; document.getElementById("demo").innerHTML = selectedText; } </script>
Alternative cleaner approach:
You can also use the selectedOptions property which directly gives you the selected option element(s) — this is more readable:
function getSelectedText() { const selectEl = document.getElementById("mySelect"); const selectedText = selectEl.selectedOptions[0].text; document.getElementById("demo").innerHTML = selectedText; }
Either way, clicking the button will now show the fruit name instead of its index number.
内容的提问来源于stack exchange,提问作者yuda fajar

