如何使用循环

时间:2017-08-23 10:12:35

标签: javascript jquery

您好我正在尝试在按下删除按钮时休息一组文本框的ID属性。

我想要做的是当按下删除按钮时读取现有的文本框并在那里停留id,因为当我删除项目时,现有ID的ID保留旧的ID值我想要休息,以匹配错误编号值。

工作jsFiddle

//Add and remove function for the error text boxes
$(document).ready(function() {
  $(document).on('click', '.addRow', function() {
    var div = $("<div />"),
      btnId = $("#stValue").val(); //Breaks the number from the ID using .match
    // btnId = $(this).data("bid").match(/\d+/);//Breaks the number from the ID using .match

    div.html(copy()); //Creates a new div container
    $('.error-Column').append(div); //Insert all the HTML into the new div

    $('#addRow_' + btnId).prop("disabled", true); //Disables the add button once clicked.
    resetErrorNo(); //Calls the reset function
  });

  //Remove the text filed from the list and resets the error number
  $(document).on('click', '.delRow', function() {
    if (confirm('Your sure you want to remove this?')) {
      var btnId = $("#stValue").val(), //Read the value of stValue
        btnId2 = btnId - 1; //Deduct 1 from the value to get the last ID

      for (var i = 0; i < btnId; i++) {
        $('.addRow').attr('id', 'addRow_' + i);
      }
      //Enables the 1st add button if the value equals 1
      if (btnId2 === 1) {
        $('#addRow_' + btnId2).prop('disabled', false);
      } else {
        $('#addRow_' + btnId).prop('disabled', false);
      }

      $(this).parent().remove(); //Remove the text row from the list.
      resetErrorNo(); //Calls the reset function
    }
  });
});

//Reset the entire error count number index
function resetErrorNo() {
  $(".errorCount").each(function(index, _this) {
    $(this).val(index + 1);
    $("#stValue").val(index + 1);
  });
}

//HTML function which will be called by the button click event for the add button
function copy() {
  var stNum = document.getElementById("stValue"),
    genNum = (document.getElementById("stValue").value - 1) + 2;

  // stNum.value = genNum;

  // language=HTML
  return '<input class="errorCount" size="1" value="' + genNum + '" style="margin-left: 2%" readonly/>\n' +
    '<select class="errorName" style="margin-left: 6%">\n' +
    '<option selected disabled>----- Select Error -----</option>\n' +
    '</select>\n' +
    '<input type="button" class="addRow" id="addRow_' + genNum + '" data-bid="addRow_' + genNum + '" value="Add" />\n' +
    '<input type="button" class="delRow" id="delRow_' + genNum + '" data-bid="delRow_' + genNum + '" value="Delete"/><br />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jType-container">
  <div id="error-Add-Container">
    <div id="error-Column-Headings">
      Error Number<span style="margin-left: 8%">Error Name</span>
    </div>
    <div class="error-Column">
      <input class="errorCount" size="1" value="1" style="margin-left: 2%" />
      <input type="hidden" value="1" id="stValue" />
      <select class="errorName" style="margin-left: 6%">
                             <option selected disabled>----- Select Error -----</option>
                         </select>
      <input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add" />
    </div>
  </div>
</div>

更新:我使用了@Rory McCrossan给出的答案并做了一些调整以得到我想要的并最终得到了我想要做的第一个下面的代码。

// Add and remove function for the error text boxes
$(document).ready(function() {
  $(document).on('click', '.addRow', function() {
    var $clone = $('.error-Column .error-container:first').clone().appendTo('.error-Column');
    $clone.find('select').val('');
    // $clone.find('input').val('');
    $('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);
    resetErrorNo();
  }).on('click', '.delRow', function() {
    var $btn = $(this);
    if (confirm('Your sure you want to remove this?')) {
      $btn.closest('.error-container').remove();
      $('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);
      resetErrorNo();
    }
  });
});

//Reset the entire error count number index
function resetErrorNo() {
  $(".errorCount").each(function(index, _this) {
    $(this).val(index + 1);
  });
}
/*----- All the styling for the error input area start -----*/

#error-Column-Headings span {
  margin-left: 8%;
}

.errorCount {
  margin-left: 2%;
}

.errorName {
  margin-left: 6%;
}

.error-Column .error-container:nth-child(1) .delRow {
  display: none;
}

.error-Column .error-container:nth-child(1) .delRow {
  display: none;
}


/*----- All the styling for the error input area end -----*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jType-container">
  <div id="error-Add-Container">
    <div id="error-Column-Headings">
      Error Number<span>Error Name</span>
    </div>
    <div class="error-Column">
      <div class="error-container">
        <input class="errorCount" size="1" value="1" style="margin-left: 2%" />
        <select class="errorName">
                                 <option selected disabled value="">----- Select Error -----</option>
                             </select>
        <input type="button" class="addRow" value="Add" />
        <input type="button" class="delRow" value="Delete" />
      </div>
    </div>
  </div>
希望这对未来的某些人有所帮助。

1 个答案:

答案 0 :(得分:1)

增量id属性是一种反模式,会导致大量不必要的维护工作 - 正如您所发现的那样。

你可以让你的代码更加干净,更简单的是通过简单地克隆每一行并使用DOM遍历找到与按钮相关的元素并根据需要添加/删除它们。试试这个:

//Add and remove function for the error text boxes
$(document).ready(function() {
  $(document).on('click', '.addRow', function() {
    var $clone = $('.error-Column .error-container:first').clone().appendTo('.error-Column');
    $clone.find('select').val('');
    $('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);
  }).on('click', '.delRow', function() {
    var $btn = $(this);
    if (confirm('Your sure you want to remove this?')) {
      $btn.closest('.error-container').remove();
      $('.addRow').prop('disabled', true).filter(':last').prop('disabled', false);
    }
  });
});
#error-Column-Headings span {
  margin-left: 8%;
}
.errorCount { 
  margin-left: 2%;
}
.errorName {
  margin-left: 6%;
}
.error-Column .error-container:nth-child(1) .delRow {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="jType-container">
  <div id="error-Add-Container">
    <div id="error-Column-Headings">
      Error Number <span>Error Name</span>
    </div>
    <div class="error-Column">
      <div class="error-container">
        <select class="errorName">
          <option selected disabled value="">----- Select Error -----</option>
        </select>
        <input type="button" class="addRow" value="Add" />
        <input type="button" class="delRow" value="Delete" />
      </div>
    </div>
  </div>
</div>