2 回答
TA贡献1876条经验 获得超6个赞
如何使用随机数据添加数据属性,例如:
<!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>
通过这种方式,您可以将数据与选项保存在一起,这样您就不需要在其他地方跟踪它。
TA贡献1871条经验 获得超8个赞
我不确定是否理解你的问题,但我认为这是一个可能的解决方案:
function myFunction() {
let messages = {
Audi: 'Haldo for: ',
BMW: 'Maldo for: ',
Mercedes: 'Baldo for',
Volvo: 'Marioldo for'
}
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = `${messages[x]} ${x}`;
}
myFunction(); // Now run the funtion for a init
我创建一个包含 n 个键的 JSON,其值为 select 的单个选项,并使用 select 的值(如选择器)来获取分配给 JSON 中键的字符串。
更新评论中的问题
<!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>
<ul id="list">
</ul>
<script>
function myFunction() {
let messages = {
Audi: {
brandName: 'Haldo for: ',
features: ['Magic', 'free', 'furry']
},
BMW: {
brandName: 'Maldo for: ',
features: ['lovely']
},
Mercedes: {
brandName: 'Baldo for',
features: ['twirling', 'tasty']
},
Volvo: {
brandName: 'Marioldo for',
features: ['bar', 'foo', 'zio']
}
}
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = `${messages[x].brandName} ${x}`;
let ul = document.getElementById("list")
ul.innerHTML = '';
for (let feat of messages[x].features) {
console.log(feat)
var li = document.createElement('li');
li.innerHTML = feat;
ul.appendChild(li);
}
}
myFunction();
</script>
</body>
</html>
- 2 回答
- 0 关注
- 111 浏览
添加回答
举报