HTML / Javascript - 通过设置选定的索引onFocus选择相同的选项两次

时间:2017-01-25 20:41:04

标签: javascript html

我正在尝试实现一个调用函数的select,即使选择了两次相同的选项也是如此。根据此thread的一个答案,我在焦点上将selectedIndex设置为-1。但是,当选择两次相同的选项时,我仍然没有得到函数调用。

var scaleSelect = new ComboBox({
      id: "scale_select",
      style: {width: "150px"},
      name: "scale_select",
      placeHolder: "Choisir une échelle",
      store: scaleStore,
      disabled: true,
      onFocus: function() {
       this.selectedIndex = -1;
       console.log(this.selectedIndex); //-1
      },
      onChange: function(value){
        mapScale = value;
        window.myMap.setScale(mapScale);
      }
    }, "scale_select");
    scaleSelect.startup();

UPDATE 尝试在onChange中设置所选索引仍然不会调用该函数 - 想知道这是否与所选索引未定义onChange的事实有关..

var scaleSelect = new ComboBox({
      id: "scale_select",
      style: {width: "150px"},
      name: "scale_select",
      placeHolder: "Choisir une échelle",
      store: scaleStore,
      disabled: true,
      onChange: function(value){
        mapScale = value;
        window.myMap.setScale(mapScale);
        var mySelect = document.getElementById("scale_select");
        console.log(this.selectedIndex) //undefined
        this.selectedIndex = -1;
        mySelect.selectedIndex = -1;
        console.log(this.selectedIndex); //-1
        console.log(mySelect.selectedIndex); //-1
      }
    }, "scale_select");
    scaleSelect.startup();

2 个答案:

答案 0 :(得分:0)

所以我认为问题在于你在选择中选择了一个值后,它就不会失去焦点。因此,除非用户实际点击页面上的其他位置,否则不会调用onFocus处理程序。如果她不这样做,那么如果她再次选择相同的值,则select的值不会触发onChange。

因此,在处理完更改之后,为什么不在onChange中设置所选索引?这样,只要您完成对当前选择的处理,您的选择就会准备好进行另一次选择。

<强>更新

好的,所以看看Dojo代码,这是我能想到的最好的代码:

var scaleSelect = new ComboBox({
  id: "scale_select",
  style: {width: "150px"},
  name: "scale_select",
  placeHolder: "Choisir une échelle",
  store: scaleStore,
  disabled: true,
  onChange: function(value){
    if(value) { // the .reset() call below will fire the onChange handler again, but this time with a null value
        mapScale = value;
        window.myMap.setScale(mapScale);
        console.log("Changed to", value, this);
        this.reset(); // This is the magic here: reset so you are guaranteed to isseu an "onChange" the next time the user picks something
    }
  }
}, "scale_select");
scaleSelect.startup();

请注意,您需要在没有值的情况下启动整个事情 - 否则初始值不会发出“onChange”事件,并且每次重置窗口小部件时,它都会返回初始值。

希望这有帮助!

答案 1 :(得分:0)

我测试了我所知道的所有事情都没有成功。我想知道你链接的线程和upvotes答案!我的原因是所选的选项不再是一个选项。但我有一个建议:

创建您自己的自定义选择

它只是一个文本框和一个div,下面有一些链接。