我在我的html表单上有几个Jquery切换效果,因为我为每个html元素使用单独的id。如何使用一个jquery函数/调用?
我现在使用的是什么:
$("#icon").click(function(){
$(".collasp").toggle("slow");
})
$("#icon2").click(function(){
$(".collasp2").toggle("slow");
})
$("#icon3").click(function(){
$(".collasp3").toggle("slow");
})
$("#icon4").click(function(){
$(".collasp4").toggle("slow");
})
$("#icon5").click(function(){
$(".collasp5").toggle("slow");
})
$("#icon6").click(function(){
$(".collasp6").toggle("slow");
})
Html(例如):
<tr>
<td colspan="3"><b>Client NI (<?php echo $numclientni; ?>)</b><a id="icon5"> +<hr></td>
</tr>
<tr>
更新
<table border="0" cellpadding="0" cellspacing="0" width="275">
<tr>
<td colspan="3"><b>Cand NI (<?php echo $num_cand; ?>)</b><a id="icon6"> +<hr></td>
</tr>
<tr>
<td width="120"></td>
<td></td>
<td align="right"></td>
</tr>
<?php
while($result = mysqli_fetch_array($get_client_cand)){
$cdid = (int) $result['cdid'];
$family_name = inputvalid($result['family_name']);
$company = inputvalid($result['company_name']);
if(strlen($company) >= 15) {
$company = substr($company, 0, 14);
}
if(strlen($family_name) >= 15) {
$family_name = substr($family_name, 0, 14);
}
echo "<tr class='collasp6' style='display:none;'>";
echo "<td>$company</td>";
echo "<td>$family_name</td>";
echo "<td align='right'><a><label class='' for='modal-15' onclick='show_cand_status($cdid, $p_id)'>Action</label></a></td>";
echo "</tr>";
}
?>
</table>
答案 0 :(得分:0)
您可以将所有JS函数压缩为一个函数,如下所示:
function onItemClick(){
$(".collasp").toggle("slow");
}
$("#icon").click(onItemClick);
$("#icon2").click(onItemClick);
$("#icon3").click(onItemClick);
$("#icon4").click(onItemClick);
$("#icon5").click(onItemClick);
$("#icon6").click(onItemClick);
或者您可以将所有图标设置为class
,例如icon
:
<a id="icon5" class="icon">...</a>
然后使用:
$('.icon').click(onItemClick);
答案 1 :(得分:0)
<tr>
<td colspan="3"><b>Client NI (<?php echo $numclientni; ?>)</b><a id="icon5" class="trigger"> +<hr></td>
</tr>
<tr>
$('.trigger').click(function(e) {
var id = $(e.target).attr('id'); //fetches id of clicked element
var no = id.replace(/[^0-9]/gi, ''); //gets number in id
$(".collasp" + no).toggle("slow"); //creates the targeted class and applies toggle effect
});