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>'
}
上面显示了我的php部分,下面的代码显示了我的jquery进程。我想要做的是,当我点击/任意按钮class=comparison
时,它会根据已选择或点击的表格行显示隐藏tr
class=matching
。但问题是,当我点击按钮时,它会显示同一类的所有tr
。
$(".comparison").on("click", function () {
if($(".matching").is(":hidden")) {
$(".matching").slideToggle("fast");
}
else {
$(".matching").hide();
}
});
如何在php while循环中选择具有相同类名的适当类?
答案 0 :(得分:5)
问题是您在使用$(".matching")
时定位所有元素。您需要使用DOM元素之间的关系并定位所需的元素。
根据当前的HTML,您可以使用.closest()
/ .parents()
遍历tr
,然后使用.next()
$(".comparison").on("click", function () {
var matching = $(this).closest('tr').next('tr.matching');
if(matching.is(":hidden")) {
matching.slideToggle("fast");
}
else {
matching.hide();
}
});
此外,HTML中的标识符必须是唯一的,因此您可以删除重复的标识符,因为您没有使用它们。
答案 1 :(得分:1)
尝试在任何地方使用$(".matching", $(this))
代替$(".matching")
。第二个参数指定您在当前对象中查找匹配的类。
您也可以创建一个变量,而不是像这样一次又一次地输入:
var matching = $(".matching", $(this))
答案 2 :(得分:0)
试试这个 -
$(".comparison").on("click", function () {
var $matching = $(this).parent().next('.matching');
if($matching.is(":hidden")) {
$matching.slideToggle("fast");
} else {
$matching.hide();
}
});