如何使用全局变量以便我可以在我的 javascript 模块上使用它

How to use global variable so i can use it on my javascript module

我想将所有这些输入值添加到我的预算应用程序中 但我无法获取单选按钮的值,因为它说它未定义。我创建全局函数以通过单选按钮值获取。但其他人在 javascript 模块中。

https://jsfiddle.net/8k3gw7ty/

<div class="button_income">
  <input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
  <label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
  <input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
  <label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
  <label class="labelinput" for="input-desc">Your Income/Expense Description</label>
  <input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
  <label class="labelinput" for="input-val">Value of Income/Expense</label>
  <input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>

实际上您的 val 变量没有默认值。由于 val 只有在您单击复选框时才会获得价值(根据您的代码)。

您还返回了 val,这是没有必要的。我还删除了 budgetController.

希望这会有所帮助。

let val = 'inc'; // default value
function getButtonValue() {
  var type = document.getElementsByName("type");
  if (type[0].checked) {
    val = type[0].value
  } else if (type[1].checked) {
    val = type[1].value
  }
}

const domController = (function() {

  return {
    getInput: function() {
      return {
        type: val,
        description: document.querySelector(".input_description").value || 0,
        value: parseFloat(document.querySelector(".input_value").value) || 0
      }


    }


  }

})();

const controller = (function( UI) {

  var ctrlAddItem = function() {
    var input = UI.getInput();
    console.log(input);

  }

  document.querySelector(".addbtn").addEventListener("click", ctrlAddItem)

  document.addEventListener("keypress", function(event) {
    if (event.keyCode === 13 || event.which === 13) {
      ctrlAddItem();
    }
  });


})( domController);
<div class="button_income">
  <input type="radio" name="type" value="inc" id="incomebtn" onclick="getButtonValue();" checked>
  <label for="incomebtn" class="income-btn">+ Add Income</label>
</div>
<div class="button_expense">
  <input type="radio" name="type" value="exp" id="expensebtn" onclick="getButtonValue();">
  <label for="expensebtn" class="expense-btn">+ Add Expense</label>
</div>
<div class="desc_input">
  <label class="labelinput" for="input-desc">Your Income/Expense Description</label>
  <input id="input-desc" type="text" class="input_description" placeholder="Salary">
</div>
<div class="value_input">
  <label class="labelinput" for="input-val">Value of Income/Expense</label>
  <input id="input-val" type="number" class="input_value" placeholder="Rp. 100.000">
</div>
<button><i class="fas fa-check addbtn">Save</i></button>