2014-12-05 4 views
2

자바 스크립트에서 동적으로 달력 (html 표)을 생성 중입니다. 토요일과 일요일 기둥을 회색 배경색으로하고 싶습니다.머리글에 따라 표 셀의 배경색을 변경하십시오.

캘린더에 다른 셀을 추가 할 때 셀 열 머리글을 확인하고 내부 HTML 텍스트/클래스/ID를 확인하고 주말 인 경우 셀의 색을 지정하고 싶습니다.

나는 일의 시작 문자로 열 헤더를 추가하는 곳은 다음과 같습니다

<th bgcolor='#c1c1c1' width=20>S</th>" 
<th width=20>M</th>" 
<th width=20>T</th>" 
<th width=20>W</th>" 
<th width=20>T</th>" 
<th width=20>F</th>" 
<th bgcolor='#c1c1c1' width=20>S</th>" 
이 코드를 시도

하지만 제대로 작동하지 않습니다 ...

var table = document.getElementById("calendarTable"); 
var rows = table.getElementsByTagName("tr"); 
for (var z = 0; z < rows.length-1; z++) { 
    for (var y = 0; y < rows[z].cells.length; y++) { 
     if(rows[z].cells[y].headers=="S") 
      rows[z].cells[y].style.backgroundColor = "#c1c1c1"; 
    } 
} 

그래서 내가 달성하고 싶습니다 전체 테이블 요소를 통해 간다 약간의 코드 스 니펫이며 innerhtml 콘텐츠 또는 ID 및 그에 따라 배경색을 변경하는 모든 셀 헤더를 확인합니다.

나중에 편집 : 테이블의

스크린 샷 :

enter image description here

것은 테이블이 우리가 현재 한달에 따라 구성되어 있는지, 그리고 우리가 반드시 모른다 토요일 또는 일요일의 지수. (사진에서 월요일에 12 월 1 일 토지이므로 꽤 운 좋은 상황입니다)

토요일과 일요일은 테이블에 고정되어 있지 않습니다. 달력은 현재 달의 1 일에 시작하여 그 다음날을 얻습니다. 나는 그것이 다소 이상하다는 것을 압니다.하지만 이것은 다른 누군가가 고안 한 것입니다. 그리고 저는 그것으로 작업해야합니다.

파란색 막대는 시간 간격을 표시하지만 이미 작동 중입니다.

전체 테이블을 구성하는 코드는 이해하기 쉽도록 길어집니다.

+1

테이블을 만들 위치에 코드를 추가하십시오. 생성시 클래스를 지정하는 것이 모든 요소를 ​​반복하고 테이블 채우기 후에 수행하는 것보다 간단 할 수 있습니다. – Zaphod

+0

테이블의 전체 렌더링 된 HTML을 포함 할 수 있습니까? 하루 헤더가 시작되기 전에 두 행이있는 것처럼 보입니다. – Pete

+0

예, 첫 번째 행은 Year (2014)이고 두 번째 행은 Month (12 월 rowspan)입니다. 2), 세 번째 행에는 날짜가 포함되어 있으며 (항상 1부터 시작), 네 번째는 날짜 헤더입니다. – Laureant

답변

2

이 시도 :

for (var z = 1; z < rows.length; z++) { 
     rows[z].cells[0].style.backgroundColor = "#c1c1c1"; // Sunday 
     rows[z].cells[6].style.backgroundColor = "#c1c1c1"; // Saturday 
} 

Example

하는 루프 일찍 행을 마무리하고

UPDATE

(헤더 행됩니다 0으로) 1에서 시작해야합니다

귀하의 수정 사항을 감안할 때 비슷한 표를 조롱하고 다음 j가 귀하의 문제를 해결해야한다고 생각합니다. :

var table = document.getElementById("calendarTable"); 
var rows = table.getElementsByTagName("tr"); 
var cellIndexes = []; 

for (var a = 0; a < rows[2].cells.length; a++) { 
    if (rows[2].cells[a].innerHTML == "S") { 
     cellIndexes.push(a + 1); 
    } 
} 

for (var z = 3; z < rows.length; z++) { 
    for (var i = 0; i < cellIndexes.length; i++) { 
     rows[z].cells[cellIndexes[i]].style.backgroundColor = "#c1c1c1"; 
    } 
} 

Example

+1

대단히 감사합니다! awesome answer – Laureant

4
: 나는 fiddle example

에 주석을 추가 한

for (var z = 3; z < rows.length; z++) { 
    for (var a = 1; a < rows[z].cells.length; a++) { 
     if (rows[2].cells[a - 1].innerHTML == "S") { 
      rows[z].cells[a].style.backgroundColor = "#c1c1c1"; 
     } 
    } 
} 

이 코드는 많은 세포를 통해 루프를 필요로하지 것처럼 성능에 약간 더 낫다

나는 스타일링을 위해 JavaScript를 사용하는 것을 권장하지 않습니다. 대신, 가능한 한 많은 CSS를 사용하여 성능을 높이고 스크립트 종속성을 낮게 유지하십시오.

테이블 구조가 다음과 같다고 가정합니다. 나는 당신의 스크린 샷에서 다시 최선을 시도 :

<table data-start-day="sun"> 
    <thead> 
     <tr> 
      <th>Year</th> 
     </tr> 
     <tr> 
      <th rowspan="2">Month</th> 
      <th>1</th><!-- fill in --><th>31</th> 
     </tr> 
     <tr> 
      <th>S</th><th>M</th><!-- fill in --> 
     </tr> 
    </thead> 
    <tbody> 
     <tr> 
      <td>Employee</td> 
      <td></td><!-- x days in month --> 
     </tr> 
     <tr> 
      <td>Exceptions</td> 
      <td></td><!-- x days in month --> 
     </tr> 
    </tbody> 
</table> 

다음으로 우리는 supported in IE 9 and up이다 화합물 선택기의 시리즈를 사용합니다.

enter image description here :

table[data-start-day=sat] thead tr:last-child th:nth-of-type(7n-13), 
table[data-start-day=sat] thead tr:last-child th:nth-of-type(7n-12), 
table[data-start-day=sat] tbody tr:nth-of-type(2n) :nth-of-type(7n-12):not(:first-child), 
table[data-start-day=sat] tbody tr:nth-of-type(2n) :nth-of-type(7n-11):not(:first-child), 
table[data-start-day=fri] thead tr:last-child th:nth-of-type(7n-12), 
table[data-start-day=fri] thead tr:last-child th:nth-of-type(7n-11), 
table[data-start-day=fri] tbody tr:nth-of-type(2n) :nth-of-type(7n-11):not(:first-child), 
table[data-start-day=fri] tbody tr:nth-of-type(2n) :nth-of-type(7n-10):not(:first-child), 
table[data-start-day=thu] thead tr:last-child th:nth-of-type(7n-11), 
table[data-start-day=thu] thead tr:last-child th:nth-of-type(7n-10), 
table[data-start-day=thu] tbody tr:nth-of-type(2n) :nth-of-type(7n-10):not(:first-child), 
table[data-start-day=thu] tbody tr:nth-of-type(2n) :nth-of-type(7n-9):not(:first-child), 
table[data-start-day=wed] thead tr:last-child th:nth-of-type(7n-10), 
table[data-start-day=wed] thead tr:last-child th:nth-of-type(7n-9), 
table[data-start-day=wed] tbody tr:nth-of-type(2n) :nth-of-type(7n-9):not(:first-child), 
table[data-start-day=wed] tbody tr:nth-of-type(2n) :nth-of-type(7n-8):not(:first-child), 
table[data-start-day=tue] thead tr:last-child th:nth-of-type(7n-9), 
table[data-start-day=tue] thead tr:last-child th:nth-of-type(7n-8), 
table[data-start-day=tue] tbody tr:nth-of-type(2n) :nth-of-type(7n-8):not(:first-child), 
table[data-start-day=tue] tbody tr:nth-of-type(2n) :nth-of-type(7n-7):not(:first-child), 
table[data-start-day=mon] thead tr:last-child th:nth-of-type(7n-8), 
table[data-start-day=mon] thead tr:last-child th:nth-of-type(7n-7), 
table[data-start-day=mon] tbody tr:nth-of-type(2n) :nth-of-type(7n-7):not(:first-child), 
table[data-start-day=mon] tbody tr:nth-of-type(2n) :nth-of-type(7n-6):not(:first-child), 
table[data-start-day=sun] thead tr:last-child th:nth-of-type(7n-7), 
table[data-start-day=sun] thead tr:last-child th:nth-of-type(7n-6), 
table[data-start-day=sun] tbody tr:nth-of-type(2n) :nth-of-type(7n-6):not(:first-child), 
table[data-start-day=sun] tbody tr:nth-of-type(2n) :nth-of-type(7n-5):not(:first-child){ 
    background:#CCC; 
} 

결과는 원하는 출력과 일치 : 주 전원을 참고 우리는 토/일 열에게 그들이 일정 자체에 가을에 상관없이 타겟팅 할 수있는 :nth-of-type의 사용을 통해

바이올린 : jQuery로 http://jsfiddle.net/80fajvd6/4/

+0

나는 동의하지만, ['] (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/col) 엘리먼트 (그리고 [ '] (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/colgroup))은 둘 다 사용되지 않으며 (HTML 4.1)/더 이상 사용되지 않습니다 (HTML 5). –

+0

@DavidThomas 너무 오랫동안 내 지식과 경험을 너무 많이 볼 정도로이 사업에 종사했습니다. " – Sampson

+0

답장을 보내 주셔서 감사합니다.하지만 서둘러서 원래 게시물을 편집해야 했으므로 언급하지 않았습니다. 하나의 사소한 일 : 토요일과 일요일은 테이블에 고정되어 있지 않습니다.달력은 현재 달의 1 일에 시작하여 그 다음날을 얻습니다. 나는 그것이 다소 이상하다는 것을 압니다.하지만 이것은 다른 누군가가 고안 한 것입니다. 그리고 저는 그것으로 작업해야합니다. – Laureant

-1

:

<!DOCTYPE HTML> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title></title> 

<style type="text/css"> 
#calendarTable th {width: 20px} 

</style>  
</head> 
<body> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 


<table id="calendarTable"> 
<th>S</th> 
<th>M</th> 
<th>T</th> 
<th>W</th> 
<th>T</th> 
<th>F</th> 
<th>S</th> 
</table> 

<script type="text/javascript"> 

$("th:contains('S')").css("background-color", "#c1c1c1"); 



</script> 
</body> 
</html> 
+0

머리글뿐만 아니라 전체 열의 색을 지정하고 싶습니다. 이 색상은 헤더에만 해당됩니다. 첫 번째 글에서 볼 수 있듯이 머리글은 이미 채색되어 있습니다. – Laureant

관련 문제