duanlanzhi5509 2018-04-16 05:16
浏览 85
已采纳

使用Jquery获取最近输入字段的POST_ID

I have a code like the following one, and I want to get the unique post_id of the corresponding post when i click on like/comment/star.

I have added a hidden input tag to store the value of the post_id of every post and trying to get the value whenever the like/comment/star is being clicked. But I couldn't get the value.

Is there any other way to achieve this? or can i go with the same logic. I am using ajax to make like/comment/star to work (no refresh). So, how can i get the post_id so that I can use the Ajax code to communicate with server.

$(".like").on("click", function() {
  var val = $(this).closest("div.post").find("input[id='post_id']").val();
  alert(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="post" id="post-1">
  <h1>
    Post Title1
  </h1>
  <input type="hidden" class="post_id" value="post_id-1">
  <img alt="Image-1">
  <img class="like">
  <img class="star">
  <img class="comment">
</div>

<div class="post" id="post-2">
  <h1>
    Post Title2
  </h1>
  <input type="hidden" class="post_id" value="post_id-2">
  <img alt="Image-1">
  <img class="like">
  <img class="star">
  <img class="comment">
</div>

....

<div class="post" id="post-n">
  <h1>
    Post Titlen
  </h1>
  <input type="hidden" class="post_id" value="post_id-n">
  <img alt="Image-n">
  <img class="like">
  <img class="star">
  <img class="comment">
</div>

</div>
  • 写回答

3条回答 默认 最新

  • dpyu7978 2018-04-16 05:25
    关注

    you can use the data attribute on the image to avoid hidden inputs and repeating unique ids :

    $(".like").on("click", function() {
      var val = $(this).data('id');
      alert(val);
    });
    .like {
      curosor: pointer;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="post" id="post-1">
      <h1>
        Post Title1
      </h1>
      <img alt="Image-1">
      <img class="like" alt="like" data-id="post_id-1">
      <img class="star">
      <img class="comment">
    </div>
    
    <div class="post" id="post-2">
      <h1>
        Post Title2
      </h1>
      <img alt="Image-1">
      <img class="like" alt="like" data-id="post_id-2">
      <img class="star">
      <img class="comment">
    </div>
    
    ....
    
    <div class="post" id="post-n">
      <h1>
        Post Titlen
      </h1>
      <img alt="Image-n">
      <img class="like" alt="like" data-id="post_id-n">
      <img class="star">
      <img class="comment">
    </div>

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗