dorv56831 2016-03-14 12:00
浏览 56

获取每个元素的id

I have blog post list and that post have comments. Posts and comments i loop with foreach from database.So i have problem when i want to create new comment via ajax. I have form and one hidden field for holding post id. When from jquery i try to access to that element post_id is all time the some. I try on submit to debug with alert to see witch post_id will be returned. All time return 270. And when i click to other post comment submit id is not changed.

Posts and comments

<?php foreach($posts as $post): ?>
   <h1><?= $post->title; ?></h1>
    <p><?= $post->text; ?></p>
    <?= if($comments = postComments($post->id): ?>
        <?= foraech($comments as $comment): ?>
             <form id="post_add">
                 <input type="text" placeholder="Say somthing..." name="comment">
                  <input type="hidden" name="pid" class="pid" value="<?= $post->id">
                  <input type="submit">
             </form>
         <?= endforeach; ?>
    <?= endif; ?>
<?= endforeach; ?>



submiteComment: function() {

        var comment_form = $("#comment_add");
        var comment_text = $(".comment_text");
        var pid = $(".pid");  // post id

        $("body").on("submit", comment_form, function(e) {
            e.preventDefault();

            alert(pid.val()); // debug all time return 270 for all comments

            if($.trim(comment_text).length) {

                $.ajax({
                    type: 'post',
                    url: baseurl + '/comment/create',
                    data: {item_id: post_id.val(), comment_text: comment_text.val()},
                    success: function(data) {
                        alert('success');
                    },
                    error: function(t, r, j) {
                        alert(r.responseText);
                    }
                })
            }
        });
  • 写回答

1条回答 默认 最新

  • drvlf9739 2016-03-14 12:11
    关注

    Because you are giving each of the post id fields in the form the same name and class, when you access it like this:

    var pid = $(".pid");

    You will receive all three of the pid elements for your comments into the variable pid. When you do pid.val() it will just return the value of the first one, which is why you will always be seeing the same pid no matter which comment you submit.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?