[JS] 별점 기능 만들기

florentyoon·2021년 7월 28일
0

js

목록 보기
9/12

별점 주기 기능 원리

1. 해당 별 index를 가져옴.

2. 해당 별 index까지 별을 채움.

3-1. 다시 클릭했을 때 해당 별 위치가 기존 채워진 별의 마지막 위치와 같으면 전부 별 비움.

3-2. 다시 클릭했을 때 해당 별 위치가 기존 채워진 별의 마지막 위치와 다르면 클릭 한 위치까지 별을 채움.

	function checkStar(){
            $('.stars span').on('click', function(){
                const arrNum = Array($(this).data().value).fill().map((v,i)=> i+1); // 클릭한 star까지 채워질 index array
                if( $(this).attr('check') === 'true' ){ // 만약 같은 위치의 별을 클릭하면 모두 비움.
                    for(let num of arrNum){
                        $('.star_'+num).children('img').attr('src', 'img/test/star.png');
                    }
                    $('.stars span').attr('check', ''); // 같은 위치가 아니므로 기존 check가 true된 별은 모두 check 해제함.
                }else{  // 같은 위치가 아니라면 해당 클릭 위치까지 별을 채움.
                    $('.stars span').attr('check', '')
                                    .children('img').attr('src', 'img/test/star.png' );
                    for(let num of arrNum){
                        $('.star_'+num).children('img').attr('src', 'img/test/star_active.png' );
                    }
                    $(this).attr('check', 'true');
                }
            });
        }
        

여기서 핵심은 현재 클릭한 별이 check 된건지 아닌지 확인하는 $(this).attr('check', 'true'); 이다.
attr은 해당 속성 값을 변경하거나 속성값 확인이 가능한데 여기서는 check 여부에 따라 기존 채워진 별인지 아닌지 확인한다.

profile
florentyoon의 IT 세상

0개의 댓글