如何定义随机数选择的jQuery selectable?

时间:2014-07-28 09:07:42

标签: jquery css selection

如何定义随机数选择的jQuery selectable? 到目前为止,如果我点击每个选择项,它们就会被选中。 但我想随机选择这些。

我的代码如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">

<style type="text/css">
#selectable .ui-selecting { background: #FECA40; }
#selectable .ui-selected { background: #F39814; color: white; }
#selectable { list-style-type: none; margin: 0; padding: 0; width: 350px;}
#selectable li { margin: 3px; padding: 1px; float: left; width: 100px; height: 80px; font-size: 4em; text-align: center; line-height: 80px; cursor: pointer; cursor: hand; }
</style>

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

<script type="text/javascript">
 $(function() {
     $( "#selectable" ).selectable({
     stop: function() {
         var result = $( "#select-result" ).empty();
         $( ".ui-selected", this ).each(function() {
             var index = $( "#selectable li" ).index( this );
             result.append( " #" + ( index + 1 ) );
        });
        }
    });
});
</script>
</head>
<body>

<ol id="selectable">
    <?php
        for($i=1;$i<=9;$i++) {
            echo "<li id=\"field_$i\" class=\"ui-state-default\">$i</li>";
        }
    ?>
</ol>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

<script>

  $(function() { // Start 'ready' listener

    $( "#selectable" ).selectable({
      //... your stuff
    });

    // Select a random <li> element
    var rand = Math.floor(Math.random() * 9) + 1; // return 1 <= rand <= 9
    $("#field_" + rand).click();

  }); // End 'ready' listener

</script>

以下是一个简单的示例:http://jsfiddle.net/Oliboy50/VLetY/