【问题标题】:How to find which option is selected in selectpicker plugin of bootstrap in canJs?如何在canJs的bootstrap的selectpicker插件中找到选择了哪个选项?
【发布时间】:2016-09-22 01:20:20
【问题描述】:

我正在使用bootstrapselectpicker 插件。现在我想找出最后选择或取消选择的选项。

<select class="selectpicker selection-criteria" multiple>
  <option value="0" selected>Mustard</option>
  <option value="1" selected>Ketchup</option>
  <option value="2" selected>Relish</option>
</select>

现在,当任何optionselecteddeselected 时,即使在canJs 中我也无法触发。但我可以在整个选择器上触发事件。

 ".selection-criteria change": function(el,ev){
    val colNames = $(el).val() // it returns all the selection options value
}

但是我可以在selectpicker 的选项点击上触发任何事件吗?当任何选项更改时,我将获得该选项并知道它现在被选中或取消选中?我可以在 canJs 中这样做吗??

编辑:如果我选择或取消选择选项 0,那么我想获取该元素,即

<option value="0" selected>Mustard</option>

根据是现在选择还是取消选择,我会隐藏一些div。

【问题讨论】:

  • 您想拥有所有选择的选项,还是想确切地知道最后选择或取消选择的东西是什么?最后你想达到什么目标?
  • 我想确切地知道最后选择或取消选择的选项
  • 你用的是can.Component还是can.Control?

标签: jquery twitter-bootstrap canjs


【解决方案1】:

这将为您提供使用 jQuery 进行更改的所有选定选项。

$('.selectpicker').change(function () {
    var selectedText = $(this).find("option:selected").text();

    alert(selectedText);
});

如果您想要最后选择的值,您可以将它们推送到数组并获取最新的 ID。 (参考:how to get the clicked option in bootstrap selectpicker?

https://jsfiddle.net/96stvL6f/

【讨论】:

  • 我想你没有理解我的问题。但是,如果之前选择了一个选项,现在我已取消选择它。所以我想要那个取消选择的选项元素。选择或取消选择无关紧要。现在确切更改哪个选项很重要。
【解决方案2】:

您应该将 &lt;select&gt; 的值绑定到 viewModel 上的属性。然后,通过为该属性定义一个设置器,您可以访问旧值和新值。我编写了代码来确定哪些项目是新选择的,哪些项目是使用 lodash 取消选择的。

http://jsbin.com/pobukubari/1/edit?html,js,output

<select {($value)}="selectedOptions" class="selectpicker selection-criteria" multiple>
  <option value="0" selected>Mustard</option>
  <option value="1" selected>Ketchup</option>
  <option value="2" selected>Relish</option>
  <option value="3" selected>Onions</option>
  <option value="4" selected>Sauerkraut</option>
</select>

...然后在您的 viewModel 中:

can.Component.extend({
  tag: "my-component",
  template: can.view('my-component-template'),
  viewModel: can.Map.extend({
    define: {
      selectedOptions: {
        set: function (newItems) {
          var prevItems = this.attr('selectedOptions');
          var union = _.union(prevItems, newItems);
          var selected = _.difference(union, prevItems);
          var deselected = _.difference(union, newItems);
          console.log('You just selected these new items:', selected.join(', '));
          console.log('You just deselected:', deselected.join(', '));
          return newItems;
        }
      }
    }
  })
});

【讨论】:

    猜你喜欢
    • 2021-07-15
    • 2013-01-26
    • 2020-01-07
    • 1970-01-01
    • 2017-05-04
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多