简化和重写我的重复代码

Simplify and rewrite my repetitive code

本文关键字:代码 我的 重写      更新时间:2023-09-26

好的,我有一个表,有单独的行或父行,有几个子行链接到父行。我有图标来删除父亲,或个别儿子。图标将显示一个模态弹出(而不是警告)来确认删除。它是有效的,但是我要重复很多次。我认为这可以简化为查找ID或类,因为模态显示/隐藏以这种方式工作。提前谢谢。

<script>
function delVesselAll(){
    $("#vessel_tab #father1").remove();
    $("#vessel_tab .son1").remove();
    document.getElementById(id).style.display = 'block';
};
function delVesselAll2(){
    $("#vessel_tab #father2").remove();
    $("#vessel_tab .son2").remove();
    document.getElementById(id).style.display = 'block';
};
</script>

我的html:

<td class="cell_50">
  <a style="text-decoration:none;" onclick="showModal('delAll1')"><img src="images/delete-row-icon1.png" title="Delete this row" height="12" width="12" class="father1Del" id="father1Del"/></a>
</td>
<div class="delModal" style="z-index:999999; margin-left:200px; margin-top:30px; display:none" id="delAll1">
  <img src="images/warning.png" />&nbsp;Are you sure you want to delete vessel and the corresponding tanks?<br />
  <input type="button" value="Cancel" class="hide" onclick="hideModal('delAll1')"/>
  <input type="button" value="Delete" onclick="delVesselAll()"/>
</div>

我基本上有很多行做同样的事情,可以有类或ID "father1" "father2" "son1" "son2"。我也希望这些div淡入和淡出,使用类似$(this).fadeIn('slow');的东西

您可以传入变量(可能通过循环,但这取决于您的数字是如何生成的):

function delVesselAll(num){
    $("#vessel_tab #father" + num).remove();
    $("#vessel_tab .son" + num).remove();
    document.getElementById(id).style.display = 'block';
};

然后这样命名:

delVesselAll(1);
delVesselAll(2);

如果你的数字是可预测的和顺序的,你可以在循环中迭代它们:

for (var i = 1; i < $("[id^='father']").length; i++) {
    delVesselAll(i);
}

如果不清楚,你可以看看这个教程