Добавление и удаление списка с тем же индексом - PullRequest
0 голосов
/ 04 октября 2019

DEMO

В моем проекте я использовал собственный список. Он работает правильно с одной стороны. Если я удалю из левой боковой панели, мне нужно разместить эту старую позицию на правой стороне.

$('#items li').click(function() {      
        var selected = [];
        selected.push($(this).html());            
         $(this).remove();        
        generateOptionElements(selected, '#selected');
    });


     populateItems('#items li');

    //populate items box with arr
    function populateItems(arr, targetMultiSelect) {
        arr.sort();
        generateOptionElements(arr, targetMultiSelect);
    }

//create option elements
function generateOptionElements(arr, targetMultiSelect) {
    for (var i = 0; i < arr.length; i++) {
        var option = document.createElement('li');    


         option.insertAdjacentHTML("beforeend",arr[i]);
        $(targetMultiSelect).append(option);


    }
}

1 Ответ

0 голосов
/ 04 октября 2019

Основным понятием фрагмента ниже является то, что вы должны создать Array из Objects и манипулировать этим в JS, а также выводить только получившиеся HTML . Это лучше, чем манипулировать DOM .

// Array of Objects - the questions and answers and other
// needed information
const questions = [{
    position: 0,
    side: 1,
    q: "0Animals giving birth to young ones:",
    a: ["Oviparous", "Oviviviparous", "Viviparous", "Both a and b"]
  },
  {
    position: 1,
    side: 1,
    q: "1Animals giving birth to young ones:",
    a: ["Oviparous", "Oviviviparous", "Viviparous", "Both a and b"]
  },
  {
    position: 2,
    side: 1,
    q: "2Animals giving birth to young ones:",
    a: ["Oviparous", "Oviviviparous", "Viviparous", "Both a and b"]
  },
  {
    position: 3,
    side: 1,
    q: "3Animals giving birth to young ones:",
    a: ["Oviparous", "Oviviviparous", "Viviparous", "Both a and b"]
  },
  {
    position: 4,
    side: 1,
    q: "4Animals giving birth to young ones:",
    a: ["Oviparous", "Oviviviparous", "Viviparous", "Both a and b"]
  },
]

// adding the created HTML to the DOM
const populateSides = questions => {

  // filling out left and right sides
  document.getElementById('right').innerHTML = questionListHtml(questions.filter(e => e.side === 1))
  document.getElementById('left').innerHTML = questionListHtml(questions.filter(e => e.side === -1))

  // adding click event listener to each question
  document.querySelectorAll('.question').forEach(e => {
    e.addEventListener('click', function(ev) {
      questions.find(el => el.position === Number(e.getAttribute('data-order'))).side *= -1
      populateSides(questions)
    })
  })

}

// template for the list
const questionListHtml = questions => {
  let html = ''
  html += '<ol>'
  questions.forEach(e => {
    html += `<li class="question" data-order="${e.position}">${singleQuestion(e)}</li>`
  })
  html += '</ol>'
  return html
}

// template for the single question
const singleQuestion = q => {
  let html = ''
  html += `${q.q}`
  html += `<ol>`
  q.a.forEach(e => {
    html += `<li>${e}</li>`
  })
  html += `</ol>`
  return html
}

populateSides(questions)
#left {
  background: red;
}

#right {
  background: yellow
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootswatch/4.3.1/cerulean/bootstrap.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <div id="left" class="col left">
    </div>
    <div id="right" class="col">
    </div>
  </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...