javascript Meteor - 在选择更改时更新 var

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16450446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:43:38  来源:igfitidea点击:

Meteor - update var on select change

javascriptdrop-down-menumeteor

提问by Kobus Post

I've got a dropdown, but when a user select another value, I want some code to be executed. My question: How can I check whether the selected value of the dropdown has changed?

我有一个下拉列表,但是当用户选择另一个值时,我希望执行一些代码。我的问题:如何检查下拉列表的选定值是否已更改?

In my html file:

在我的 html 文件中:

<template name="jaren">    
    <form id="yearFilter">
        <select class="selectpicker span2" id="yearpicker" >
            {{#each jaren}}
                {{#if selectedYear}}
                <option selected value="{{_id}}">{{jaar}} {{description}}</option>
                {{else}}
                <option value="{{_id}}">{{jaar}} {{description}}</option>
                {{/if}}
            {{/each}}
        </select> 
    </form>
</template>

in my javascript file:

在我的 javascript 文件中:

Template.jaren.jaren = function() {
  return Years.find();
}
Template.jaren.selectedYear = function() {
  if (Session.get('year_id') == this._id) {
    return true;
  } else {
    return false;
  }
}
Template.jaren.events({
  'change form#yearFilter #yearpicker': function(event, template) {
    Session.set('year_id', template.find('#yearpicker').value);
    console.log("value changed");
  }
});

回答by Rahul

You can get the value of the select element inside the event handler and then compare it to the old value you had already stored:

您可以在事件处理程序中获取 select 元素的值,然后将其与您已经存储的旧值进行比较:

"change #yearpicker": function(evt) {
  var newValue = $(evt.target).val();
  var oldValue = Session.get("year_id");
  if (newValue != oldValue) {
    // value changed, let's do something
  }
  Session.set("year_id", newValue);
}

回答by Daniel Budick

A solution with pure JavaScript would be:

使用纯 JavaScript 的解决方案是:

'change #yearpicker': function (event) {
  var currentTarget = event.currentTarget;
  var newValue = currentTarget.options[currentTarget.selectedIndex].value;
  if(!Session.equals('year_id', newValue)){
    Session.set('year_id', newValue);
  }
}