我正在尝试使用动态ID控制按钮 $ num表示按钮的数量 但是这段代码不起作用,因为点击变量$ i在退出循环时会取相同的值: 我该如何解决这个问题?
$(document).ready(function(){
$num=("#num").attr("value");
for ($i=0;$i<=$num;$i++){
$("#createNew"+$i).click(function(){
$("#j"+$i).hide();
$("#cNew"+$i).slideToggle(1000);
});
$("#join"+i).click(function(){
$("#cNew"+$i).hide();
$("#j"+$i).slideToggle(1000);
});
}
});
php代码:
while ($row=mysqli_fetch_array($result1)){
echo "<div class=\"well project\">";
echo"<h1 id=\"course\">".$row['courseID']." </h1></br>";
echo "<p>".$row['description']."</p></br></br>";
echo "<input type=\"button\" class=\"btn btn-default bt\" id=\"createNew\"value=\"create new\" >";
echo "<input type=\"button \" class=\"btn btn-default bt\" id=\"join\" value=\"join\">";
echo "<div id=\"cNew".$i."\" style=\"display:none\"></br><form method=\"POST\" action=\"createNewProject.php?reg=".$row['regID']."\" ><label for=\"title\" >Project title</label><input type=\"textbox\" class=\"form-control\" name=\"title\"></br><label for =\" Pdescription\">description</label><textarea name=\"Pdescription\" class=\"form-control\"></textarea></br> <input type=\"submit\" vlaue=\"create\" class=\"btn btn-default bt\" ></form></div>";
echo"</br></br><div id=\"j".$i."\" style=\"display:none\"><form method=\"post\" action=\"joinProject.php?reg=".$row['regID']."\"><label for=\"pId\">Enter the project ID</label><input type=\"textbox\" class=\"form-control\" name=\"pId\"></br> <input type=\"submit\" value=\"Send requst\" class=\"btn btn-default bt\"></br></form></div>";
echo "</div>";
$i++;
}
}
else
echo"<div class=\"well project\"><h1>No new projects</h1></div>";
echo "<input type=\"textbox\" id=\"num\" value=\"".$i."\" style=\"display:none\">";
答案 0 :(得分:1)
最好只为此使用事件委托。我们也可以使用动态数字作为选择器的一部分。
$('body').on('click', '[id^="createNew"], [id^="join"]', function(){
var id = $(this).prop('id').split('createNew')[1];
$('#j'+id).hide();
$('#cNew'+id).slideToggle(1000);
});
$('body').on('click', '[id^="join"]', function(){
var id = $(this).prop('id').split('join')[1];
$('#cNew'+id).hide();
$('#j'+id).slideToggle(1000);
});
实施将起作用something like this: