[英]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.