簡體   English   中英

如何 DRY javascript 代碼以最小化冗余

[英]How to DRY javascript code to minimize redundancy

當涉及到 DRYing 代碼時,我是 Javascript 的新手。 有人可以幫我干燥這個javascript代碼嗎

這是 JS 代碼從以下位置獲取數據的地方:

<div class="form-group">
    @Html.LabelFor(model => model.eMP.EMPNO, "Employee Number", htmlAttributes: new { @class = "control-label" })
    @Html.EditorFor(model => model.eMP.EMPNO, new { htmlAttributes = new { @class = "form-control", @id = "EMPNO" } })
    @Html.ValidationMessageFor(model => model.eMP.EMPNO, "", new { @class = "text-danger" })
</div>

這就是價值應該去的地方:

<div class="form-group">
    @Html.LabelFor(model => model.Emp_educ.EMPNO, "EMPNO", htmlAttributes: new { @class = "control-label" })
    @Html.EditorFor(model => model.Emp_educ.EMPNO, new { htmlAttributes = new { @class = "form-control", @id = "EMPNOEDUC", readOnly = "readonly" } })
    @Html.ValidationMessageFor(model => model.Emp_educ.EMPNO, "", new { @class = "text-danger" })
</div>

到目前為止,這是我的代碼,我目前正在嘗試最小化代碼的冗余。 有沒有辦法干掉這段代碼?

$(document).ready(function () {
    $("#EMPNOEDUC").val($("#EMPNO").val());
    $("#EMPNOJOBHIST").val($("#EMPNO").val());
    $("#EMPNOREFERENCE").val($("#EMPNO").val());
    $("#EMPNOLICENSES").val($("#EMPNO").val());
});

向輸入添加一個類,然后您可以在一行中設置值$("#EMPNO").val()

$(document).ready(function () {
    $(".myinputs").val($("#EMPNO").val());
});

您可以在組合的 jQuery 選擇器中列出目標 ID,如下所示:

$("#EMPNOEDUC, #EMPNOJOBHIST, #EMPNOREFERENCE, #EMPNOLICENSES").doSomething(...)

演示:

 $(document).ready(function() { $("#EMPNOEDUC, #EMPNOJOBHIST, #EMPNOREFERENCE, #EMPNOLICENSES").val($("#EMPNO").val()); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> Source:<br /> <input id="EMPNO" value="123456" /><br /> <br /> Targets:<br /> <input id="EMPNOEDUC" /><br /> <input id="EMPNOJOBHIST" /><br /> <input id="EMPNOREFERENCE" /><br /> <input id="EMPNOLICENSES" /><br />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM