簡體   English   中英

根據條件在jQuery中選擇隨機值

[英]select random value based on condition in Jquery

請參閱以下html

<div class="testclass" style="top:30px;">msg1</div>
<div class="testclass" style="top:60px;">msg2</div>
<div class="testclass" style="top:80px;">msg3</div>
<div class="testclass" style="top:100px;">msg4</div>
<div class="testclass" style="top:200px;">msg5</div>

選擇小於623且該隨機值不是元素停止樣式的隨機值,即不是30、60、80、100、200。但是這些值會改變。 而且該隨機值需要與最高值至少相距30。 這個怎么做 。

<!DOCTYPE html>
<html>
<head>
  <title>hello</title>
</head>
<body>

  <div class="testclass" style="top:30px;">msg1</div>
  <div class="testclass" style="top:60px;">msg2</div>
  <div class="testclass" style="top:80px;">msg3</div>
  <div class="testclass" style="top:100px;">msg4</div>
  <div class="testclass" style="top:200px;">msg5</div>

  <button>Generate Random number</button>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

  <script>

    function isNotValid(arr, val){ // checks if the random value is valid
      var check = false;

      $.each(arr, function(v){
            if(val < (v+30)){
              check = true;
              return;
            }
      });

      return check;
    }    

    function getRandomNum(max, min) { // getting random value
      return parseInt(Math.random() * (max - min) + min);
    }

    $(document).ready(function(){
        $("button").click(function(){
            var topValues = [];

            $(".testclass").each(function(){ // stores [30, 60, 80, 100, 200] in topValues variable
               topValues.push(parseInt($(this).css('top')));
            });

            var randomValue = 0;

            do{
                 randomValue = getRandomNum(623, 0); // max, min for fetching random value. You can pass the smallest topValues as min to optimize the process
            } while(isNotValid(topValues, randomValue)); // fetch random value until its not valid


            alert(randomValue); // alert random value
        });
    });

  </script>

</body>

以上是完整的工作代碼,但可以更完善。 我相信這會幫助您

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM