有什么选择可以用循环将div ID降低1吗?

时间:2019-01-13 14:04:47

标签: javascript jquery

我有一个具有以下ID的div列表:en_1en_2en_3en_4。我建立了一个div删除按钮,预期的结果是,当我删除en_2时,所有其他div的数字ID(例如_2_4等)都将大于被删除的div。降低一个。

$(document).ready(function(){
	for (var is = 1; is <= 4; is++) {
		$('#delete_' + is).on('click', {is}, function(e) {
		  var deleted = e.data.is;
		  $('#en_' + deleted).remove();
		  for(var set = (deleted + 1); set <= 4; set++) {
			$('#en_' + set).attr({id: 'en_'+(set-1)});
		  }
		}
	}
});

我希望删除div id = en_2并将en_3更改为en_2,并将en_4设置为en_3

但目前的状态是我希望所有的div都低一-已删除。

2 个答案:

答案 0 :(得分:0)

我在您的代码中发现的主要问题是,用于删除和切换ID的功能位于for循环中。

解决方案是将函数移到for循环之外

$(document).ready(function(){
  function removeElement(index) {
    return function(e) {
      var deleted = e.data.is;
      $('#en_' + deleted).remove();
      for(var set = (deleted + 1); set <= 4; set++) {
        $('#en_' + set).attr({id: 'en_'+(set-1)});
      }
    }
  }
  for (var is = 1; is <= 4; is++) {
    $('#delete_' + is).on('click', {is}, removeElement(is));
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div id="en_1">a</div>
<div id="en_2">b</div>
<div id="en_3">c</div>
<div id="en_4">d</div>

<button id="delete_1">1</button>
<button id="delete_2">2</button>
<button id="delete_3">3</button>
<button id="delete_4">4</button>

答案 1 :(得分:0)

使用jQuery

https://jsfiddle.net/r1t063ha/1/

<div id="en_1" class="counter">Content in 1<button>Delete</button></div>
<div id="en_2" class="counter">Another Content<button>Delete</button></div>
<div id="en_3" class="counter">Third<button>Delete</button></div>
<div id="en_4" class="counter">Four<button>Delete</button></div>
<div id="en_5" class="counter">¿?<button>Delete</button></div>
<div id="en_6" class="counter">Jeje<button>Delete</button></div>
<div id="en_7" class="counter">On sale<button>Delete</button></div>

js

$(function(){
    $('button').click(function(){
    let div = $(this).closest('div')
    let idDiv = $(div).attr('id')
    let numberDeleted = idDiv.split('_')[1]
    div.remove()

    let divs = $('.counter')

    $.each(divs, function(i, v){
        let id = $(v).attr('id')
      let number = id.split('_')[1]
      if (number > numberDeleted ) {
        $(v).attr('id', `en_${number - 1}`)
        console.log(number)
      }
    })
  })
})