函数return on on not working

时间:2017-01-16 20:38:58

标签: javascript

我有一个选择选项菜单,我想用于多个功能,但我没有在每个函数周围包装这个代码,而是我没有在它之外创建变量,所以我可以使用它。现在我尝试返回变量并调用该函数,但它仅在第一个函数中起作用,并且在我选择其他选项时不会被触发。

实现这一目标的最佳方法是什么?

<select id="level_select" onchange="LevelName()">
                    <option select disabled>Select Level</option>
                    <option value="2d" id="high_water_pass_1">Highwater Pass 1</option>
                    <option value="2e" id="high_water_pass_2">Highwater Pass 2</option>
</select>

var name = LevelName();

function LevelName() {
    level = $('#level_select').find(":selected").attr("id");
    return level;
}

console.log(name);

2 个答案:

答案 0 :(得分:0)

您应该在函数内调用console.log

function LevelName() {
   level = $('#level_select').find(":selected").attr("id");
   console.log(level);
   return level;
}

您的console.log实际上已被触发。

答案 1 :(得分:0)

这是一个工作小提琴:https://jsfiddle.net/gdb2xod8/2/

除了脚本本身的位置,我真的没有改变任何东西,点击javascript齿轮,你会注意到我把它放在头脑中

你需要把你的脚本放在你的html之前,头部是个好位置:

<html>
<head>
<script>
  //script here, or better, reference your script in the src attribute
  var name = LevelName();

  function LevelName() {
    level = $('#level_select').find(":selected").attr("id");
    console.log(level)
    return level;
  }

  console.log(name);
</script>
</head>
<body>
  <select id="level_select" onchange="LevelName()">
    <option selected disabled>Select Level</option>
    <option value="2d" id="high_water_pass_1">Highwater   Pass 1</option>
    <option value="2e" id="high_water_pass_2">Highwater Pass 2</option>
</select>
</body>
</html>

另外,我将“select”属性更改为“selected”。应该给你你期待的行为。

相关问题