首页 > 解决方案 > JS 函数参数已声明但从不读取

问题描述

我在 html 中有一个输入,并希望将输入的文本放入 JS 上的一个对象中并显示在

结果在html上标记。因为我不想简化代码,所以我尝试创建一个函数(以便我可以为每个对象属性调用它。 <input type="text" placeholder="Typ" id="type-mhouse" /> 是输入。

const land = {
  Type: "",
  Adress: "",
  Value: "",
  updateValue: function (x, y, z) {
    this.x = document.getElementById(y).value;
    document.getElementById(z).textContent = this.x;
    console.log(this[0]);
  },
};

是JS。

<p class="ergebnis" id="ergtype-house"></p>

是显示结果的位置。

问题是:当我在输入中键入例如“Flat”时,它会在 html 输出中正确显示,但 land.Type 仍然是“”。

我已经尝试了一切,但我对 JS 还是很陌生,所以我无法解决它。(我也知道我不应该将东西命名为“类型”或“值”。我会改变它。)

感谢您的任何评论!

重要编辑:土地对象在链接的 js 文件中使用。单击按钮时在 HTML 中调用该函数:

<script>
        $(document).ready(function () {
          
          //Button on Modal
          $("#submit").click(function () {
           
            land.updateValue("Type", "type-mhouse", "ergtype-house");

          });
        });
      </script>

标签: javascriptfunctionobjectfunction-parameter

解决方案


我不确定你想做什么,但这里有一个解决你的问题的解决方案。

const land = {
  type: "",
  address: "",
  value: "",
  updateValue: function(landAttributeName, textElementId, displayElementId) {
    this[landAttributeName] = document.getElementById(textElementId).value;
    document.getElementById(displayElementId).innerText = this[landAttributeName] || '';
  },
};

顺便说一句,你是对的,你应该使用更容易理解的名字:-)

计算机科学中只有两个难点:缓存失效和命名。——菲尔·卡尔顿


推荐阅读