如何限制功能中的重复行?

时间:2018-07-31 19:33:16

标签: jquery

我有一个对话框将由不同的链接触发。如果单击“添加”链接,则对话框应该没有预填充。否则,所有输入字段都将预先填充相应的信息,具体取决于我单击的链接。

最初,我具有所有这些功能

function prefillItemName(clickedItemNameLink) {
    $('.update-item-name').val($(clickedItemNameLink).text());
  }

  function prefillPriceLevelPrice(clickedItemNameLink) {

    $('#pricelevel-price').val($(clickedItemNameLink).attr('data-pl-p'))
  }

  function prefillItemPrice(clickedItemNameLink) {
    $('.update-item-price').val($(clickedItemNameLink).attr('data-item-price'));
  }

  function prefillItemCode(clickedItemNameLink) {
    $('.update-item-code').val($(clickedItemNameLink).attr('data-item-code'));
  }

  function prefillItemPrice(clickedItemNameLink) {
    $('.update-item-price').val($(clickedItemNameLink).attr('data-item-price'));
  }

  function presetDepartment(clickedItemNameLink) {
    //get clicked item's department name
    let currentDepartmentName = $(clickedItemNameLink).attr('data-item-department');
    let selectedDepartment = $('.select-department option:contains(' + currentDepartmentName + ')');
    //remove old selected
    if($('.select-department option:selected').length > 0){
        $('.select-department option:selected').removeAttr('selected');
    }
    //Checks for the option element which contains the department name, then sets the attribute selected to that option
    if (selectedDepartment !== null) {
      selectedDepartment.attr('selected', 'selected');
      selectedDepartment.prop('selected', true);
    }
  }

  function presetVendor(clickedItemNameLink) {
    //get clicked item's vendor name
    let currentVendorName =
    $(clickedItemNameLink).attr('data-item-vendor');
    let selectedVendor = $('.select-vendor option:contains(' + currentVendorName + ')');
    //remove old selected
    if($('.select-vendor option:selected').length > 0){
        $('.select-vendor option:selected').removeAttr('selected');
    }
    //Checks for the option element which contains the vendor name, then sets the attribute selected to that option
    if (selectedVendor !== null) {
      selectedVendor.attr('selected', 'selected');
      selectedVendor.prop('selected', true);
    }
  }

但是现在,由于我需要检查单击的链接(“添加”链接没有ID),因此我要添加例如:

function prefillItemName(clickedItemNameLink) {
   this line --> let strName = '';
   this line -->  if ($(clickedItemNameLink).attr('id')) {
   this line -->  strName = ...;
    }
    $('.update-item-name').val(strName); <-- put strName inside ()
  }

这些行将重复。我想知道如何重用相同的代码?我正在考虑使用构造函数,但我只知道如何对简单对象使用构造函数。

0 个答案:

没有答案