Javascript 变量打印

标签 javascript html

我有 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/

相关文章:

javascript - 如何在没有 .get 的情况下获取主干模型属性

javascript - 云函数问题,查询生成数组?

javascript - 计算多个输入的总和 - jQuery Range Slider

javascript - HTML radio 和复选框输入组合?

javascript - 为网站添加书签 Javascript 而不是 jquery

javascript - 根据 Vue 中的数据变化切换对象(使用 Vuex)

javascript - jScrollPane Vertical Tabs - 如何模拟点击链接/标签?

javascript - 使用 Angular JS 时如何在 ng-repeat 内的 img 标签中显示图像?

javascript - 使用 node.js 注册/登录示例

javascript - 使 HTML 表单元素出现(jQuery 或 JS)