在循环内获取特定的按钮ID和div ID

时间:2013-12-02 06:28:57

标签: jquery

请有人知道这个逻辑吗?我想制作按钮和div的特定id,每当我点击特定帖子时,按钮'x'(这是发布的del按钮)就会出现。我无法在jQuery中正常运行所以请帮忙。任何想法都会得到高度赞赏。谢谢:)这是代码:

var r = 0;
while(r < 2000){
r++;
$("#groups").on('click', '#post_tbl'+r, function(){

    $("#delpost1"+r).toggle("fast");

});}

以及循环的div和按钮:

<?php

$c = 0;
while($c < 2000)
{
$c++;
echo "<div id='post_tbl$c' >";
echo "POST"; // I don't include the whole code for looping post from database for simplicity of my question 
echo "<button id='delpost$c' style='display: none;' >x</button>";
echo "</div>";

}

?>

2 个答案:

答案 0 :(得分:0)

将div的id放在其自己的位置而不是将其附加到循环中每个id的末尾对我来说更有意义。

例如:在PHP中,将id包含在隐藏变量中

<div class="post_tbl">
     <input class="post_id" type="hidden" value='<?php echo $c; ?>' />
     <button class="delete">X</button>
</div>

在jquery中,单击X - 查找最近的ID。

$('.delete').on('click', function() {
    var id = $(this).closest('.post_id').val();
    // do stuff with id
});

答案 1 :(得分:0)

<?php

$c = 0;
while($c < 2000)
{
$c++;
echo "<div id='post_tbl$c' class='postclass' >";
echo "POST"; // I don't include the whole code for looping post from database for     simplicity of my question 
echo "<button class='togglebutton' id='delpost$c' style='display: none;' >x</button>";
echo "</div>";

}

?>

和jquery

$(document).on('click','.postclass',function(){
  $(this).find('.togglebutton').toggle('fast');
});

在这种情况下你不需要使用任何ID

无论如何,如果你试图再次使用相同类型的元素,尝试使用类而不是id,除非强制需要它

相关问题