如何在php while循环中选择具有相同类名的适当类

nzr*_*nty 2 php jquery

while($row = mysqli_fetch_array($stmt)) {
 output .= '<tr>
             <td id=compare><button class=comparison>Search</button></td>
            </tr>
            <tr id=matching class=matching>
             <td colspan=12>None of a data was found</td>
            </tr>'
}
Run Code Online (Sandbox Code Playgroud)

上面显示了我的php部分,下面的代码显示了我的jquery进程.我想要做的是,当我点击一个/任何按钮class=comparison,它会显示隐藏tr这是class=matching基于表的行已选择或点击.但问题是,当我点击按钮时,它会显示所有tr相同的类.

$(".comparison").on("click", function () {
     if($(".matching").is(":hidden")) {
         $(".matching").slideToggle("fast");
     }
     else {
         $(".matching").hide();
     }
});
Run Code Online (Sandbox Code Playgroud)

如何在php while循环中选择具有相同类名的适当类?

Sat*_*pal 5

问题是您在使用时定位所有元素$(".matching").您需要使用DOM元素之间的关系并定位所需的元素.

根据当前的HTML,您可以遍历tr使用.closest()/ .parents() 然后立即找到它的兄弟使用.next()

$(".comparison").on("click", function () {
     var matching = $(this).closest('tr').next('tr.matching');
     if(matching.is(":hidden")) {
         matching.slideToggle("fast");
     }
     else {
         matching.hide();
     }
}); 
Run Code Online (Sandbox Code Playgroud)

此外,HTML中的标识符必须是唯一的,因此您可以删除重复的标识符,因为您没有使用它们.