2017-04-03 5 views
0

私は動的にPOSTリクエストを作成する要素にIDを割り当ててから、別の要素にクラスを追加する必要があります。 アヤックス - 動的ポスト要求のためのボタンを作成

は基本的に、私は、行を作成し、foreachループでJSPページを持っている..私は本当にJSとのnoobので、私は私が混乱したと思います。最後に、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

まず...あまりにも動作します。あなたがクリックされた要素を選択してもらうことは、親はあなたまで右続きますainer。 あなたが多分行う必要がある例の上に。

$(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

関連する問題