2017-04-03 1 views
0

POST 요청을 만들고 다른 요소에 클래스를 추가하기 위해 요소에 ID를 동적으로 할당해야합니다. 난 정말 JS와 멍청한 놈이야, 그래서 내가 엉망이라고 생각해.Ajax - 게시물 요청을위한 버튼을 동적으로 생성합니다.

기본적으로, 나는 행을 만듭니다 forEach 루프와 JSP 페이지가 있습니다. 마지막으로 POST 요청을 보내는 클릭 링크가 있습니다. 요청 (부울 T/F)의 결과로 요소에 클래스를 적용해야합니다.

문제는 스크립트에 전달할 동적 ID를 만드는 방법과 POST 결과에 따라 클래스를 추가하는 방법을 선택하는 것입니다.

내 JSP는

가 정확하지의 $("#${notification.notificationId"}) 때문에 스크립트는 분명히

$(document).ready(function(){ 
    $("#${notification.notificationId").closest('a').click(function(){ 
      $.ajax({ 
       type: 'POST', 
       url: '/${notification.notificationId}', 
       dataType: 'text', 
       success: function (text) { 
        $("#${notification.notificationId"}).addClass("font-bold"); 
        alert(text); 
       }) 
     }) 
    }) 

가 작동하지 않는 것입니다 (내가 모르는이 foreach 루프

<c:forEach items="${notifications }" var="notification"> 
    <tr id="${notification.notificationId }"> 
     <td class="actions pull-right"><a href="#"> <i class="fa fa-gear"></i></a></td> 
    </tr> 
</c:forEach> 
이있는 경우 스크립트의 나머지 작품도 마찬가지입니다 ...

+0

대신 할 수있는 일은 데이터 속성을 tr에 할당하는 것입니다. IE : data-notification-id = "$ {notification.notificationId}". 또한 클릭 할 수있는 각 클릭에 클래스를 추가하십시오. 그런 다음 jquery 클래스 ($ '. tr-class')를 사용하십시오. ('click', function (e) {var id = $ (this) .data ('notification-id') .... 나머지 물건 ...}) – Budhead2004

답변

0

먼저 클릭 링크 행 컨테이너를 가져와야합니다. 클릭 한 요소를 선택하고 오른쪽 cont까지 부모가됩니다. 승객. 위의 예를 참조하십시오.

$(document).ready(function() { 

    $("tr > td > a").on("click", function (e) { 
     // This will prevent your link to navigate to "#" 
     e.preventDefault(); 

     // This is the container row of the link that was clicked 
     var $tr = $(this).parent().parent(); 

     // The ajax request 
     $.ajax({ 
     type: "post", 
     url: "/" + $tr.attr("id"), // This will take the ID of the row container. Eg: ID=1 it will navigate to "/1" 
     dataType: "text", 
     success: function (response) { 
      // I presume that you response will be either "true" or "false" like you mention 
      // So, if the response is "true", then we add the class to the row container 
      if (response == "true") { 
      $tr.addClass("font-bold"); 
      } 

     }); 

     }); 

    }); 

}); 

행운을 빈다.

+0

고마워요! 그것은 일했다! – besmart

관련 문제