【问题标题】:detect change of selectmenu in jquery mobile 1.4检测 jquery mobile 1.4 中选择菜单的变化
【发布时间】:2014-03-01 07:17:30
【问题描述】:

在几个版本都没有使用 JQM 之后,我正在重新审视它。

我有一个简单的选择框

<select name="current-option" id="current-option" class="current-option" data-native-menu="false">
        <option>Select Option</option>
        <option value="1">option 1</option>
        <option value="2">option 2</option>
    </select>

我希望能够检测到此选择框中的更改,然后读取它的值。似乎典型的 jquery 方法不起作用,我在 api 中没有看到此事件:http://api.jquerymobile.com/selectmenu/

【问题讨论】:

  • 是否支持 onchange 等标准事件?
  • 没有。那就是问题所在。下面的 2 个答案在正常环境中工作,但在 jQuery mobile 1.4 中不工作。一旦页面被初始化,selectmenu 实际上就变成了一个按钮并且选择框被隐藏了。 Onchange 不会触发。
  • 菜单本身变成一个按钮,还是每个选项?
  • Alok 的答案有效,但必须包含在文档就绪函数中

标签: javascript jquery jquery-mobile select-menu


【解决方案1】:

你需要的事件是'selectmenuchange',jQuery mobile会触发这个事件来选择而不是'change'。

应该是这样的:

    $('#current-option').on('selectmenuchange',function () {
       $('#thelabel').text($(this).val());
    });

【讨论】:

    【解决方案2】:

    在生成选择菜单后,我查看了 DOM。看起来 select-menu 插件将创建一个div,其 id 类似于select 的 id;在这种情况下,它将是current-option-listbox。这个div 的子代由几个东西组成,包括选项。基于此,我想出了以下解决方案:

    var currentValue = ""; // keep track of the selected value
    
    $('.ui-btn-inner', '#current-option-listbox').click(function () {
        if ('a', this).text() !== currentValue) {
            // the value changed - do stuff
            currentValue = $(this).children('a').text();
        }
    });
    

    这在很大程度上取决于插件的渲染方法保持不变,或者在开发人员维护插件的使用时,代码是围绕设计的。我相信这会让你得到你所需要的。

    这是Fiddle Demo

    【讨论】:

      【解决方案3】:

      好的,您想知道更改事件发生后选择的选项的值;您应该执行以下操作:--

      $('#current-option').change(function () {
        var optionSelected = $(this).find('option:selected');
        //var optTextSelected = optionSelected.text();
        var optValueSelected = optionSelected.val();
      });
      

      我会要求您更改您的选择标签的名称、ID 和类名。

      【讨论】:

        【解决方案4】:

        这不是在移动环境中,而是使用移动插件:Fiddle

        HTML

        <select name="current-option" id="current-option" class="current-option" data-native-menu="false">
            <option>Select Option</option>
            <option value="1">option 1</option>
            <option value="2">option 2</option>
        </select>
        <label id='thelabel'></label>
        

        JavaScript

        $('#current-option').change(function () {
            $('#thelabel').text($(this).val());
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-09-11
          • 1970-01-01
          • 1970-01-01
          • 2012-04-04
          相关资源
          最近更新 更多