我的事件监听器只触发一次,甚至没有运行代码而没有错误?

时间:2016-07-29 20:27:25

标签: javascript select

我正在尝试基于select语句执行一个非常基本的if-then代码,但它似乎不起作用。我一加载窗口就创建了一个事件监听器,但它似乎只根据我添加的console.log语句运行一次。

我希望当我在选择中更改为其他选项时,值会更改或提示将出现(取决于所选内容)。相反,一切都没有发生。

我还通过JS Hint运行我的代码以尝试查找小错误,而且Chrome或控制台的控制台都没有抛出任何错误。

我看过这个答案,试着记住如何获取所选选项的值:Get selected value in dropdown list using JavaScript?

选择代码:

<select name="type_of_service" id="type_of_service">
                    <option selected="selected">Choose one...</option>
                    <option value="optgroup_1">Every time</option>
                    <option value="optgroup_2" name="trigger-describe_interval">On an interval...</option>
                    <option value="optgroup_3">Completely optional</option>
                </select> 

Javascript功能&amp;事件监听器:

// The following is a list of event listeners. We need to start it off with a making sure the body has loaded first.

window.addEventListener("load", function () {
  console.log("Checkpoint 1");
  // Add more listeners here...
  var type_of_service = document.getElementById("type_of_service");
  type_of_service.addEventListener("change", trigger_describe_interval());
});
// This funciton is for the selector, with the ID of type_of_service

function trigger_describe_interval() {
  console.log("Checkpoint 2");
  var selected_object = document.getElementById('type_of_service');
  var current_value = selected_object.options[selected_object.selectedIndex].value;
  // So now we've aquired the value of the select.
  // If the value is optgroup_1, then change the described_interval to 3500 miles
  if (current_value == "optgroup_1") {
    document.getElementById('described_interval').value = "1";
  }
  // Otherwise, if the option is optgroup_2 then ask for an interval
  else if (current_value == "optgroup_2") {
    // create a prompt varible
    var response = prompt("Enter the interval in miles. For example, if you would like this service to be used every 3500 miles, enter '3500'");
    // Ensure that this is a integer
    if (response !== parseInt(response, 10)) {
      // So now it's not a number, tell them that
      response = window.alert("Sorry, but \"" + response + "\"is not a valid entry. Please try again. ");
      // loop back
      trigger_describe_interval();
      // abort this version of the function
      return false;
    }
  }
}

1 个答案:

答案 0 :(得分:2)

尝试从此函数调用中删除括号:

type_of_service.addEventListener("change", trigger_describe_interval());

像这样:

type_of_service.addEventListener("change", trigger_describe_interval);

如果需要将参数传递给inside函数,可以通过执行以下操作来实现:

type_of_service.addEventListener("change", function() {
    trigger_describe_interval(param1, param2);
});

编辑:在上述评论中归功于imtheman,他们还提到在我回答之前删除括号。