3

我为每个循环构建了一个从数据库中拉回几行的循环。它拉出的每一行都有一个链接,以及一个隐藏的输入框,其值为 posting_id。此链接在某种程度上类似于 facebook 上的点赞按钮。隐藏的输入框只存储了posting_id。当您单击“喜欢”链接时,它会将 posting_id 发送到一个 jQuery 页面并 ping 回一个名为 community 的页面,告诉它用户已经“喜欢”了该帖子。

这就是问题所在

我拉了几行,当您单击“喜欢”按钮时,似乎只有被拉的第一行实际上正在将数据发送到 jQuery 页面。如果我单击除顶部按钮之外的任何其他“喜欢”按钮,它将根本不起作用。

jQuery 页面

$('.bump_link').click(function(){ 
    var posting_id = $('.posting_id').val();    
    $.post("community.php", {
        posting_id: posting_id
    });
    alert(posting_id);
    $(this).toggleClass("bumped"); 
});

Foreach 循环

foreach ($result as $value) {
    $group_postings .= '
    <input type="text" class="posting_id" value="'.$value['posting_id'].'"> 
    <div id="bump_icon" class="bump_link"></div>
    <span id="counter"></span>
    ';
}

我希望我已经把这个问题说清楚了,它曾经而且很难解释。

4

5 回答 5

2

问题是您正在使用一个类来获取posting_id,因为所有隐藏字段都具有相同的类,无论您单击什么按钮,都只会传递第一个元素值。

我建议使用这个 html,没有隐藏输入,将值作为数据属性传递

<div id="bump_icon" class="bump_link" data-postid="'.$value['posting_id'].'">

并在这个js中,从数据属性中获取发布ID

$('.bump_link').click(function(){ 
   var posting_id = $(this).data('postid'); // get the posting id from data attribute
   $.post("community.php", {
       posting_id: posting_id
   });
   alert(posting_id);
   $(this).toggleClass("bumped"); 
});
于 2013-03-27T11:47:02.677 回答
1

你的问题是这一行:

var posting_id = $('.posting_id').val();    

这将每次返回第一个 posting_id 值,而不是与您单击的 bump_link 关联的值。

有很多方法可以解决这个问题。一种方法是使用 .prev() 选择前一个元素:

var posting_id = $(this).prev('.posting_id').val();

这会从当前 div 中选择上一个 posting_id 元素。这取决于 posting_id 元素位于关联的 bump_link div 之前的事实。

于 2013-03-27T11:42:05.920 回答
1

您正在调用val()选择器,您可能会返回一个以上的元素,但val()只会给您一个(第一个)元素的值。您可以使用map()获取具有类的所有输入值posting_id

var posting_id_values = $('.posting_id').map(function(){
       return this.value;
}).get().join(',');    
于 2013-03-27T11:38:34.367 回答
0

如果您只想发送posting_id点击按钮的,您可以像这样更改您的 PHP/HTML 代码:

foreach ($result as $value) {
    $group_postings .= '
    <div id="bump_icon" class="bump_link">
    <input type="text" class="posting_id" value="'.$value['posting_id'].'"> 
    </div>
    <span id="counter"></span>
    ';
}

你的JS代码是这样的:

$('.bump_link').click(function(){ 
    var posting_id = $(this).find('.posting_id').val();    
    $.post("community.php", {
        posting_id: posting_id
    });
    alert(posting_id);
    $(this).toggleClass("bumped"); 
});
于 2013-03-27T11:41:41.707 回答
0

use on delegated event since you are adding the content dynamically and

$(this).prev('.posting_id') // to get the posting data value

$(document).on('click','.bump_link',function(){ 
  var posting_id = $(this).prev('.posting_id').val(); //<-- use $(this)  reference 
  $.post("community.php", {
      posting_id: posting_id
  });
 alert(posting_id);
 $(this).toggleClass("bumped"); 
});
于 2013-03-27T11:43:11.077 回答