Javascript 语法 getElementById outerHTML

我有一个关于 outerHTML 语法的问题。也有可能我的思路错了。


我的html文件如下:


<!DOCTYPE html>

<html>

<body>

<label for="language">Choose a language:</label>

<select name="language" id="language" value="val1">

<option value="val1">English</option>

<option value="val2">German</option>

</select>

<p>You selected: <span id="language"></span></p> <!-- shall display either "English" or "German" -->

<p>You selected the following option: <span id="language"></span></p> <!-- shall display either "val1" or "val2" -->

<script  src="./script.js"></script>

</body>

</html>

我指的是一个脚本,目前唯一的内容是


var selectedlang = document.getElementById("language").outerHTML;

在 html 文件中,它应显示它的值和变量。我不知道如何进行。


收到一只叮咚
浏览 126回答 1
1回答

慕容森

一个文档中不能有多个具有相同id值的元素;您当前的标记使用id="language"三个不同的元素。您至少需要更改其中两个。我想你问的是如何:在两个 s 中显示当前选择的选项的文本和值span,以及如果用户更改选择,如何更新您显示的内容。如果您只想要选定的值,则可以使用元素value的属性select。但是对于文本和值,您需要selectedIndex属性和options集合:function showTextAndValue(select, textSpan, valueSpan) {&nbsp; &nbsp; const option = select.options[select.selectedIndex];&nbsp; &nbsp; if (option) {&nbsp; &nbsp; &nbsp; &nbsp; textSpan.textContent = option.text;&nbsp; &nbsp; &nbsp; &nbsp; valueSpan.textContent = option.value;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; // No option is selected&nbsp; &nbsp; &nbsp; &nbsp; textSpan.textContent = "";&nbsp; &nbsp; &nbsp; &nbsp; valueSpan.textContent = "";&nbsp; &nbsp; }}在那个例子中,我让它接受了select和spans 作为函数的参数。您将在页面加载时调用该函数,然后在 的事件触发时再次select调用input。这是一个例子:const select = document.getElementById("language-select");const textSpan = document.getElementById("text-span");const valueSpan = document.getElementById("value-span");function showTextAndValue(select, textSpan, valueSpan) {&nbsp; &nbsp; const option = select.options[select.selectedIndex];&nbsp; &nbsp; if (option) {&nbsp; &nbsp; &nbsp; &nbsp; textSpan.textContent = option.text;&nbsp; &nbsp; &nbsp; &nbsp; valueSpan.textContent = option.value;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; // No option is selected&nbsp; &nbsp; &nbsp; &nbsp; textSpan.textContent = "";&nbsp; &nbsp; &nbsp; &nbsp; valueSpan.textContent = "";&nbsp; &nbsp; }}// Show on page loadshowTextAndValue(select, textSpan, valueSpan);// Hook the `input` eventselect.addEventListener("input", () => {&nbsp; &nbsp; // Update the contents of the elements&nbsp; &nbsp; showTextAndValue(select, textSpan, valueSpan);});<label for="language">Choose a language:</label><select name="language" id="language-select" value="val1"><option value="val1">English</option><option value="val2">German</option></select><p>You selected: <span id="text-span"></span></p> <!-- shall display either "English" or "German" --><p>You selected the following option: <span id="value-span"></span></p> <!-- shall display either "val1" or "val2" --><script&nbsp; src="./script.js"></script>(请注意,我更改了所有三个id。)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript