본문 바로가기

트러블 슈팅

for문 id값 따로주기

문제점

ajax콜을 get타입으로 가져와, .append메소드를 이용하여 카드들을 붙이는 코드를 짜는 과정에서

id값이 중복적으로 들어가는 문제가 발생, 결과적으로 input이 재대로 이루어 지지 않았다

//get 타입을 이용, db에서 데이터 가져오기
function game() {
            $('#cards-box').empty()
            $.ajax({
                type: "GET",
                url: "/game",
                data: {},
                success: function (response) {
                    let rows = response['games']
                    let temp_html = ``
                    //for문을 활용해서 db리스트데이터를 나누고
                    for (let i = 0; i < rows.length; i++) {
                        let title = rows[i]['title']
                        let url = rows[i]['url']
                        let comment = rows[i]['comment']
                        let num = rows[i]['num']
                        //.append 메소드를 이용해서 추가
                        temp_html = `<div class="card" style="width: 18rem;">
                                    <img src=${url} class="card-img-top" alt="...">
                                    <div class="card-body">
                                        <h5 class="card-title">${title}</h5>
                                        <p class="card-text">${comment}</p>
                                        //이 부분이 문제가 되었음 ;;
                                        <input id="saveComment" class="mycomment">
                                        <a href="#" class="btn btn-primary" onclick=show_input(${num})>댓글 남기기</a>
                                    </div>
                                </div>`
                        $('#cards-box').append(temp_html)
                    }
                }
            })
        }

2번째 "라, 마, 바"가 저장되지 않는 모습

몰랐던점

id값이 중복되어 붙어버린 경우였고 이런 경우 어떻게 해결할 수 있을까 구글링을 해보았지만,

특별한 성과는 없었다...

for($i=0; $row=sql_fetch_array($result); $i++) {  //while을 사용해도 상관없음.

   $j = $i + 1;

   echo "<ul id='test".$j."'>";

이러한 코드도 발견했지만 활용을 하지 못했기 때문..

그래서 나 나름대로 부족한 지식을 총동원해서

<input id="saveComment-`${num}`" class="mycomment">

이나

<input id="${num}" class="mycomment">

아얘 id값을 정수값도 줘보았지만 전부 실패했다...

 

해결

아직 해결을 하지 못한상태이다 해결하게 된다면 다시 올려보겠다