[英]Pass multiple values to jQuery
我为每个循环构建了一个从数据库中拉回几行的循环。 它拉出的每一行都有一个链接,一个隐藏的输入框,其值为posting_id。 这个链接在某种程度上类似于facebook上的类似按钮。 隐藏的输入框只存储了posts_id。 当您单击“喜欢”链接时,它会通过posting_id发送到jQuery页面并回显一个名为community的页面,告诉用户“喜欢”该帖子。
这是问题所在
我正在拉几行,而且当你点击“喜欢”按钮时,似乎只有拉出的顶行实际上是将数据发送到jQuery页面。 如果我点击除了顶部之外的任何其他“喜欢”按钮,它将完全不起作用。
Jquery Page
$('.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>
';
}
我希望我已经明确了这个问题,而且很难解释。
问题是您正在使用类来获取posting_id,因为所有隐藏字段都具有相同的类,只有第一个元素值被传递,无论您单击什么按钮。
我建议使用这个html,没有隐藏的输入,将值作为数据属性传递
<div id="bump_icon" class="bump_link" data-postid="'.$value['posting_id'].'">
在这个js中,从data属性中获取发布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");
});
您在选择器上调用val()
可能会返回多个元素,但val()
将仅为您提供一个(第一个)元素的值。 您可以使用map()获取具有类posting_id
所有输入值
var posting_id_values = $('.posting_id').map(function(){
return this.value;
}).get().join(',');
你的问题是这一行:
var posting_id = $('.posting_id').val();
这将每次返回第一个post_id值,而不是与您单击的bump_link相关联的值。
有很多方法可以解决这个问题。 一种方法是使用.prev()来选择前一个元素:
var posting_id = $(this).prev('.posting_id').val();
这将从当前div中选择前一个posting_id元素。 这依赖于posts_id元素位于关联的bump_link div之前的事实。
如果您只想发送单击按钮的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");
});
on
动态添加内容时使用委托事件
$(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");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.