본문 바로가기
Front-End/Javascript

[jquery] 동적 생성된 객체 선택(지정) 하는법

by LeeGangEun 2022. 7. 6.

Ajax를 이용해서 댓글리스트를 구현하는중이였다.

이 부분을 html에 미리 생성하지 않고,

$('#comment-btn').click(function () {
            var data={trip:trip, star:star, content:reviewContent.val(),writer:inputWriter.val()};
            console.log(data);
            $.ajax({
                url:'/reply/'+trip,
                type:"POST",
                data:JSON.stringify(data),
                contentType:"application/json; charset=utf-8",
                dataType:"text",
                success:function(result){
                    $("#replyCount").html(result);
                    getTripReply()
                    self.location.reload();
                }
            })
        });

        function getTripReply() {
            function formatTime(str) {
                var date=new Date(str);

                return date.getFullYear()+'/'
                    +(date.getMonth()+1)+'/'+
                    date.getDate()+' '+
                    date.getHours()+':'+
                    date.getMinutes();
            }

            $.getJSON("/reply/"+trip+"/all",function (arr) {
                var str="";
                var rno;

                $.each(arr,function (idx,reply) {
                    console.log(reply)

                    str+='<li id="replyList"> '
                    str+='<i class="fa-solid fa-user" id="comment-icon"></i>'

                    str+='<div class="comment-all-box">';

                    str+='<div class="comment-id-box">'
                    str+='<span id="userId">'+reply.writer+'</span>';
                    str+='<span>'+formatTime(reply.regDate)+'</span>';

                    str+='<div id="comment-btn">';
                    str+='<span class="btn" id="modifyBtn"><i class="fa-solid fa-pencil"></i></span>';
                    str+='<span class="btn" id="removeBtn"><i class="fa-solid fa-xmark"></i></span>';
                    str+='</div>';

                    str+='</div>';
                    str+='<div class="comment-content-box">';
                    str+='<span id="reviewText">'+reply.content+'</span>'
                    str+='</div>'

                    str+='<span class="replystar" data-star2='+reply.star+' data-rno='+reply.rno+' data-trip='+reply.trip+'></span>';


                    str+='</div>'
                    str+='</li>'
                });

                $(".TripReplyList").html(str);

                $(".replystar").each(function(idx,o){
                    $(this).starrr({rating:$(this).data("star2"),readOnly:true});
                });
            });
        }

 

등록 버튼을 클릭했을때 동적으로 댓글 목록이 생성되게 구현하니까,

저 부분을 지정할 수가 없는것이였다.......

jquery.min.js:2 Uncaught ReferenceError: removeBtn is not defined at HTMLDocument.<anonymous>

이런오류가 뜨며 아주 어지러운 상태였지만..

 $("#removeBtn").on('click',function (){
            console.log("삭제버튼");
            var data = {rno: rno};
            console.log(data);

            $.ajax({
                url:'/reply/'+trip +"/"+ rno ,
                type:"DELETE",
                contentType:"application/json; charset=utf-8",
                dataType:"text",
                success: function(result){
                    self.location.reload();
                    $("#replyCount").html(result);//reivew count update
                    getTripReply();
                }
            })
 });

 

이런식으로 되어있는 코드를 아래와 같이 바꾸니까 해결되었다..

$(document).on('click',  " #removeBtn ", function (){
            console.log("삭제버튼");
            var data = {rno: rno};
            console.log(data);

            $.ajax({
                url:'/reply/'+trip +"/"+ rno ,
                type:"DELETE",
                contentType:"application/json; charset=utf-8",
                dataType:"text",
                success: function(result){
                    self.location.reload();
                    $("#replyCount").html(result);//reivew count update
                    getTripReply();
                }
            })
        });

 

-----------------추가 ---------------------------------
위와같이 docment.on으로 하지말고 상위 태그에 on 거는게 좋다.
docment는 너무 최상위 태그이기 때문이다 !~

<script th:inline="javascript">
    $(document).ready(function (e) {
        var security = $('.security').val();
        var targetReview = $(this);
        var replyWriter = targetReview.find('#userId').text().trim();
        var star = 0;
        $('.starrr').starrr({
            rating: star,
            change: function (e, value) {
                if (value) {
                    console.log(value);
                    star = value;
                }
            }
        });

        var trip = [[${dto.bno}]];

        var inputWriter = $(".security");

        var reviewContent = $(".comment-content");

        inputWriter.val("");
        reviewContent.val("");

        $('#comment-btn').click(function () {
            var data = {trip: trip, star: star, content: reviewContent.val(), writer: inputWriter.val()};
            console.log(data);
            $.ajax({
                url: '/reply/' + trip,
                type: "POST",
                data: JSON.stringify(data),
                contentType: "application/json; charset=utf-8",
                dataType: "text",
                success: function (result) {
                    $("#replyCount").html(result);
                    getTripReply()
                    self.location.reload();
                }
            })
        });

        function getTripReply() {
            function formatTime(str) {
                var date = new Date(str);
                var year = date.getFullYear().toString();
                year.substr(2,4);

                return year + '.'
                    + (date.getMonth() + 1) + '.' +
                    date.getDate();
            }

            $.getJSON("/reply/" + trip + "/all", function (arr) {
                var str = "";

                $.each(arr, function (idx, reply) {
                    console.log(reply)

                    str += '<li class="replyList"> '
                    // str += '<i class="fa-solid fa-user" id="comment-icon"></i>'

                    str += '<div class="comment-all-box">';

                    str += '<div class="comment-id-box">'
                    str += '<span  id="userId">' + reply.writer + '</span>';
                    str += '<input type="hidden" name="userId" value="'+reply.writer+'">';

                    str += '<span>' + formatTime(reply.regDate) + '</span>';

                    str += '<div id="comment-btn-star">';
                    str += '<span class="replystar" data-star2=' + reply.star + 'data-trip=' + reply.trip + '></span>';
                    str += '<span class="btn removeBtn" data-writer='+reply.writer+' data-rno=' + reply.rno +'><i class="fa-solid fa-xmark"></i></span>';

                    // str += '<span class="btn" id="modifyBtn"><i class="fa-solid fa-pencil"></i></span>';
                    str += '</div>';
                    str += '</div>';
                    str += '<div class="comment-content-box">';
                    str += '<span id="reviewText">' + reply.content + '</span>'
                    str += '</div>'

                    str += '</div>'
                    str += '<input type="hidden" name="rno" value="'+reply.rno+'">';
                    str += '<input type="hidden" name="writer" value="'+reply.writer+'">';
                    str += '</li>'
                });

                $(".TripReplyList").html(str);

                $(".replystar").each(function (idx, o) {
                    $(this).starrr({rating: $(this).data("star2"), readOnly: true});
                });
            });
        }

        getTripReply();
        $(".TripReplyList").on('click',".removeBtn",function (){
            console.log("삭제버튼");

            var rno;
            var replyId;
            var writer;
            var targetReview = $(this);
            console.log(targetReview);
            var data = {rno: rno, writer: writer};

            replyId = targetReview.data("writer");
            rno = targetReview.data("rno");

            console.log("댓글번호는 : "+rno);
            console.log("댓글 아이디: " +replyId);
            console.log("삭제 버튼 : :"+data);
            console.log("로그인한 유저는: "+ security);
            console.log("-------------------------");

            if(security == null || security == ""){
                modalOn();
                return false;
            }


            var con = confirm("댓글을 삭제하시겠습니까?");


            if(con == true && security == replyId){
                $.ajax({
                    url: '/reply/' + trip + "/" + rno,
                    type: "DELETE",
                    contentType: "application/json; charset=utf-8",
                    dataType: "text",
                    success: function (result) {
                        self.location.reload();
                        $("#replyCount").html(result);//reivew count update
                        getTripReply();
                    }
                })
            }else if(con == true && security != replyId){
                alert("내가 쓴 글이 아닙니다.");
            }else{
                return false;
            }
        });

    });