所以基本上我想要的是创建一个隐藏的段落,当选择每个值时,隐藏的段落会显示我为每个值设置的自定义文本。所以基本上,如果我选择奥迪,我想输入:Random Text / for BMW> Whatever / Mercedes> car,

重点是针对所选的每个值自定义其显示的文本

完全需要这个,所以任何帮助都将不胜感激!



    <!DOCTYPE html>
<html>
<body>

<p>Select a new car from the list.</p>

<select id="mySelect" onchange="myFunction()">
  <option value="Audi">Audi
  <option value="BMW">BMW
  <option value="Mercedes">Mercedes
  <option value="Volvo">Volvo
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>

<p id="demo"></p>

<script>
function myFunction() {
  var x = document.getElementById("mySelect").value;
  document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>

</body>
</html>

最佳答案

如何添加带有随机数据的data属性,例如:

    <!DOCTYPE html>
<html>
<body>

<p>Select a new car from the list.</p>

<select id="mySelect" onchange="selectionChanged(this)">
  <option value="Audi" data="random audi data">Audi
  <option value="BMW" data="random bmw data">BMW
  <option value="Mercedes" data="random mercedes data">Mercedes
  <option value="Volvo" data="random volvo data">Volvo
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>

<p id="demo"></p>

<script>
function selectionChanged(selectObj) {

  var carData = selectObj.options[selectObj.selectedIndex].getAttribute('data');

  var x = document.getElementById("mySelect").value;
  document.getElementById("demo").innerHTML = "You selected: " + x+ " with car data "+carData;
}
</script>

</body>
</html>

这样,您可以将数据与选项保持在一起,因此您无需在其他位置跟踪数据。

10-06 04:25