如何以编程方式 select jQuery 滑块?

How to programmatically select jQuery slider?

我正在尝试在 jQuery 移动设备中预先 select 一个滑块。

<select name="box" id="box" data-role="slider" data-mini="true">
    <option value="off" selected></option>
    <option value="on" >mit</option>
</select>

这在某种程度上不起作用:$("#box").val("on").flipswitch( "refresh" ) ;

因此我通过 PHP 和 preselect:

创建了盒子
<select name="box" id="box" data-role="slider" data-mini="true">
        <?php
        $box['on'] = 'mit'; 
        $box['off'] = '';   
        foreach ($box as $key => $value) {
                ($key == $_GET['box']) ? $isselected = ' selected=""' : $isselected = false;
            echo '<option value="'.$key.'" '.$isselected .'>'.$value.'</option>';
        } 
    ?>
</select>

导致:

<select name="box" id="box" data-role="slider" data-mini="true">
    <option value="on"  selected="">mit</option>
    <option value="off" ></option>
</select>

但在这种情况下,开关看起来像这样(缺少蓝色):

如何 select 一个值,最好是 jQuery?

JQM 文档在这里有些混乱。 flipswitch有两种:

  1. 建立在 select 元素之上的翻转开关
  2. 建立在 checkbox 元素之上的翻转开关

(不知道为什么还有一个slider翻转开关)

两者的皮肤都像手机 flippswitches,您可以根据需要自由使用 selectcheckbox,完全一样使用标准 HTML 非移动元素的方式:如果您需要从 PHP 构建页面,则使用 selectedchecked 属性预先-select一个option/value.

下面是一个从代码初始化的例子:

$(document).on("flipswitchcreate", "#flip-checkbox", function(e) {
  $(this).prop("checked", true).flipswitch("refresh");
});

$(document).on("flipswitchcreate", "#flip-select", function(e) {
  $(this).val("on").flipswitch("refresh");
});

$(document).on("slidecreate", "#flip-slider", function(e) {
  $(this).val("on").slider("refresh");
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  <link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
  <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
  <script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.js"></script>
</head>
<body>
  <div id="page-one" data-role="page">
    <div role="main" class="ui-content">
      <label for="flip-checkbox">Flip toggle switch checkbox:</label>
      <input type="checkbox" data-role="flipswitch" id="flip-checkbox" name="flip-checkbox">
      <label for="flip-select">Flip toggle switch select:</label>
      <select data-role="flipswitch" id="flip-select" name="flip-select">
        <option value="off" selected="">Off</option>
        <option value="on">On</option>
      </select>
      <label for="flip-slider">Flip toggle switch slider:</label>
      <select data-role="slider" id="flip-slider" name="flip-slider">
        <option selected="" value="off">Off</option>
        <option value="on">On</option>
      </select>
    </div>
  </div>
</body>
</html>


关于 active 状态,你是对的。我也注意到了,所以我在 CSS:

中默认使用它
/* Maybe forgotten in JQM standard CSS */
a.ui-flipswitch-on {
    color: inherit !important;
}