簡體   English   中英

獲取每個元素的ID

[英]Get id for each element

我有博客文章列表,該文章有評論。 帖子和評論我循環從foreach從數據庫。所以我有問題,當我想通過ajax創建新的評論。 我有表格和一個隱藏的字段,用於保存帖子ID。 當我從jquery嘗試訪問該元素時, post_id始終是一些。 我嘗試使用警報進行調試以查看是否返回女巫post_id 所有時間返回270。當我單擊其他帖子評論時,提交ID不會更改。

帖子和評論

<?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);
                    }
                })
            }
        });

因為您以相同的名稱和類的形式為每個帖子ID字段提供了名稱,所以當您像這樣訪問它時:

var pid = $(".pid");

您將收到所有三個pid元素,以便您對變量pid進行注釋。 當您執行pid.val() ,它將僅返回第一個的值,這就是為什么無論您提交哪個評論,您總是會看到相同的pid。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM