2014-11-21 3 views
0

사용자가 정수를 입력하는 텍스트 상자가 있습니다. 그런 다음 사용자가 입력 한 정수까지 번호를 나열하려고합니다. 목록은 처음에는 빨간색으로, 두 번째로 노란색으로, 세 번째로 녹색으로 표시됩니다. 이 패턴은 다시 반복 될 것입니다. 네 번째처럼 빨간색, 다섯 번째는 노란색, 여섯 번째는 녹색 등입니다.반복 패턴을 얻는 방법

사용자가 12를 입력하면 1 (빨간색), 2 (노란색), 3 (녹색), 4 (빨간색), 5 (노란색) ... so on..till 12.

나는 EVen과 Odd를 기준으로 정수를 구별 할 수 있지만이 경우에는 빨강, 노랑, 초록의 세 가지 옵션이 있습니다.

+1

봐 (https://developer.mozilla.org/en-US/docs입니다 /Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder_(.25)) - http://jsfiddle.net/arunpjohny/Lhg3pL56/1/ –

+0

색상은 CSS에서 [nth-child selector]를 사용하여 쉽게 할 수 있습니다 (https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child). – nnnnnn

답변

1

숫자를 루프로 쉽게 생성 할 수 있다고 생각합니다. 지금까지 패턴을 식별하는가는대로, 당신은 단순히이 검사 (의사 코드)를 할 수있는 :

num are values generated from 1 to whatever you want to be. 

(num - 1) % 3 = 0 --> Color should be red 
(num + 1) % 3 = 0 --> Color should be yellow 
    num % 3 = 0  --> Color should be green 

은 당신이 올바른 방향으로 시작 할텐데.

1

은 무엇 당신이 찾고있는 것은 [나머지 연산자]에서 remainder operator

var num = 12; 
 
var list = [], 
 
    colors = ['red', 'green', 'blue']; 
 
for (var i = 0; i < num; i++) { 
 
    list.push('<span class="' + colors[i % colors.length] + '">' + (i + 1) + '</span>') 
 
} 
 

 
var html = list.join(''); 
 
//add it to the dom to view 
 
$('body').append(html);
.red { 
 
    color: red; 
 
} 
 
.green { 
 
    color: green; 
 
} 
 
.blue { 
 
    color: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

4
<?php 
     $limit = 10; 

     $color = array('red','yellow','green'); 

     for($i=0;$i<=$limit;$i++) 
      { 
       echo "<span style='color:".$color[$i%3]."'>$i</span>"; 

      } 

    ?> 
관련 문제