我的页面包含从数据库中检索到的记录列表,当您单击某些span
元素时,它会更新数据库,但目前这仅适用于要显示的第一条记录。
(基本上将0改为1,反之亦然)
这是我在页面上的两个html元素,它们在循环中回显:
Featured:<span class="featured-value">'.$featured.'</span>
Visible:<span class="visible-value">'.$visible.'</span>
这就是我所拥有的:
$(document).ready(function() {
$('.featured-value').click(function() {
var id = $('.id-value').text();
var featured = $('.featured-value').text();
$('.featured-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$('.featured-value').html(data);
$('.featured-value').fadeIn('slow');
}
});
return false;
});
// same function for a different span
$('.visible-value').click(function() {
var id = $('.id-value').text();
var visible = $('.visible-value').text();
$('.visible-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&visible="+visible,
success: function(data) {
$('.visible-value').html(data);
$('.visible-value').fadeIn('slow');
}
});
return false;
});
});
使用id属性的工作正常但现在我正在使用类,成功查询的fadeIn
部分无效,但我希望.each
能解决这个问题。< / p>
更新 完整循环如下:
while ($event = $db->get_row($events, $type = 'MYSQL_ASSOC'))
{
// open event class
echo '<div class="event">';
echo '<div class="id"><span class="row">Event ID:</span><span class="id-value"> '.$id.'</span></div>';
echo '<div class="featured"><span class="row">Featured: </span><span class="featured-value">'.$featured.'</span></div>';
echo '<div class="visible"><span class="row">Visible: </span><span class="visible-value">'.$visible.'</span></div>';
echo '</div>';
}
答案 0 :(得分:3)
Cymen对于id选择器是正确的,导致你遇到麻烦。此外,我决定为你重构。可能需要一些调整,但不是一切?
function postAndFade($node, post_key) {
var id = $node.parents('.id').find('.id-value').text();
var post_val = $node.text();
$node.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&"+post_key+"="+post_val,
success: function(data) {
$node.html(data);
$node.fadeIn('slow');
}
});
return false;
}
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
答案 1 :(得分:2)
点击功能在每次点击时获得相同的ID和值,因为您已将其绑定到该类。相反,您可以利用event.target,假设这些值在被单击的项目上。如果没有,您需要使用event.target并导航到该行中的项目。
$('.featured-value').click(function(event) {
var $target = $(event.target);
var id = $target.attr('id');
var featured = $target.text();
$target.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$target.html(data).fadeIn('slow');
}
});
return false;
});
所以类似的东西,但它可能无法正常工作,因为它需要根据您的HTML进行自定义。