我有 C++ 背景,但对我尝试使用 Javascript 做的事情有一些疑问。我需要制作一个伪类,因为 Javascript 没有它们。我基本上想根据选择的内容打印不同的东西。我在这个例子中只定义了两个“水果”,但我要做的会用到更多。任何帮助将不胜感激。我知道这有一些缺陷,比如 select 没有以任何方式链接到 fruit 函数。
<!DOCTYPE html>
<html>
<script>
function select_fruit(name)
{
var fruit_name = name;
}
function fruit(name, color, amt)
{
this.name = name;
this.color = color;
this.amt = amt;
}
apple = new fruit("apple", "red", 5);
orange = new fruit("orange", "orange", 1);
document.getElementById("name").innerHTML = name;
document.getElementById("color").innerHTML = color;
document.getElementById("amt").innerHTML = amt;
</script>
<body>
<select name="pick_these" onchange="fruit(this.value)">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select><br />
<p>I want *amt *color *fruit</p><!--This should say I want 5 red apple, if it's selected on the dropdown-->
</body>
</html>
最佳答案
首先,您缺少 <head>
标签。除此之外,你需要移动你的document.getElementById.....
行到 select_fruit()
功能,并更改onchange
事件调用 select_fruit
反而。以下是我将如何做您正在尝试的事情:
HTML:
<select id="fruitlist">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select>
<p id="result"></p>
JS:
window.onload = function() { // or just `(function() {` if script is after above HTML
var fruits = {
"apple":{
"color":"red",
"amt":5
},
"orange":{
"color":"orange",
"amt":1
}
}, result = document.getElementById('result');
document.getElementById('fruitlist').onchange = function() {
var selection = this.options[this.selectedIndex].value;
result.innerHTML = "I want "+fruits[selection].amt+" "
+fruits[selection].color+" "+selection;
};
}; // or `})();` if you used `(function() {` at the start
关于Javascript 变量打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15556340/