Как я могу переместить элемент списка в первую позицию, а затем обратно? - PullRequest
3 голосов
/ 14 октября 2019

Я пытаюсь адаптировать этот код к своим спискам li. [enter image description here Я набросал что-то, что показывает точную логику.

  • Кликающий элемент идет первым!

  • Второй нажатый элемент идет первым, а предварительный просмотр - последним.

Это код:

$('ul li').each(function() {

    var $this = $(this).data({
            position: $(this).index()
        }),
        $table = $this.closest('ul'),
        $input = $this.find('input');

    $input.bind('click', function(e) {
        var $first = $table.find('li:first'),
            position;

        if ($(this).is(':checked')) {
            position = $first.data('position');
            $table.find('li input').not($(this)).removeAttr('checked');
            if (position != 0) $first.insertAfter($table.find('li').eq(position));
            $this.prependTo($table);
        } else if ($this.data('position') != 0) {
            position = $this.data('position');
            $this.insertAfter($table.find('li').eq(position));
        }
    });

});

У меня есть код ниже, который работает с таблицами, но я хотел бы реализовать это на ul li. Есть ли способ сделать так, чтобы вход флажка стал тегом li или anchor?

Демо

Ответы [ 3 ]

1 голос
/ 14 октября 2019

Если вы не хотите использовать флажок, но используете простые теги, посмотрите этот пример:

См. В JSFiddler: http://jsfiddle.net/nfywg06b/5/

Я не переименовал переменные, поэтомучто легко понять важные корректировки.

Используйте переменную goToLast, чтобы определить поведение: отправить на последнюю позицию или изменить позицию (устаревшее поведение)

jQuery:

var goToLast = true;

$('.item').each(function() {

  var $this = $(this).data({
      position: $(this).index()
    }),
    $table = $this.closest('.container'),
    $input = $this;

  $input.bind('click', function(e) {
    $input.toggleClass('selected');

    var $first = $table.find('.item:first'),
      position;

    if ($(this).hasClass('selected')) {
      position = !goToLast ? $first.data('position') : $table.children().length - 1;
      $table.find('.item').not($(this)).removeClass('selected');
      if (position != 0) $first.insertAfter($table.find('.item').eq(position));
      $this.prependTo($table);
    } else if ($this.data('position') != 0) {
      position = $this.data('position');
      $this.insertAfter($table.find('.item').eq(position));
    }
  });

});

HTML:

<div class="container">
  <a href="#" class="item">1</a>
  <a href="#" class="item">3</a>
  <a href="#" class="item">A</a>
  <a href="#" class="item">B</a>
  <a href="#" class="item">C</a>
</div>

CSS:

a.item {
  display: block;
  background-color: silver;
  border: 1px solid gray;
  padding: 10px;
  margin: 10px;
}

a.item.selected {
  background-color: green;
}
1 голос
/ 14 октября 2019

Исходя из вашего примера, я предполагаю, что у вас нет контроля над источником HTML, и вы хотите динамически изменить таблицу на список.

Вот пример (с комментариями), основанный на вашем коде и оригиналепример html.

Довольно прямо:

//Unique table selector that is targeted to be parsed and replaced:
var $targetTable = $("table"); 
//This is the target new list that will store the list items:
var $sudoul = $("<ul></ul>");
//Toggle through all the rows and create a list item:
$targetTable.find('tr').each(function () {
    
    $sudoul.append($("<li style='border:1px solid black; cursor:pointer'>" + $(this).text() + "</li>")
           //This binds a click event to the new LI stored in $sudoul
           .bind("click", function(){
						
            //if we click the first element avoid and don't to anything:
            if ($(this).is(':first-child')) return;
						
            var $container = $(this).closest("ul");
            var $this      = $(this); // The clicked item to move UP.
            var $first     = $container.find("li").eq(0); // The first list item to be replaced.
            
            //First move the item to the head of the list:
            $container.prepend($this.data("alreadyclicked", true));
            
            //Check if the first element was already moved the append it to the end of the list
            if ($first.data("alreadyclicked")) $container.append($first);

          })
          .data({alreadyclicked: false }) // this flag is set to true when the element is clicked
    );
});
//Replace the table with the newly created list:
$targetTable.replaceWith($sudoul);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<table>
    <tbody>
        
    <tr>
        <td><input type="checkbox" /></td>
        <td>1</td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td>3</td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td>A</td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td>B</td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td>C</td>
    </tr>
    
    </tbody>
</table>
1 голос
/ 14 октября 2019

Внесение некоторых корректировок в код JSFiddle работает следующим образом:

См. Пример здесь: http://jsfiddle.net/z0bga89t/

См. Код HTML выше:

<ul>
    <li>
        <input type="checkbox" />
        1
    </li>
    <li>
        <input type="checkbox" />
        3
    </li>
    <li>
        <input type="checkbox" />
        A
    </li>
    <li>
        <input type="checkbox" />
        B
    </li>
    <li>
        <input type="checkbox" />
        C
    </li>
</ul>

И jQuery:

$('li').each(function () {
    var $this  = $(this).data({position: $(this).index()}),
      $table = $this.closest('ul'),
      $input = $this.find('input');

  $input.bind('click', function (e) {
    var $first = $table.find('li:first'),
        position;

    if ($(this).is(':checked')) {
        position = $first.data('position');
        $table.find('li input').not($(this)).removeAttr('checked');
        if (position != 0) $first.insertAfter($table.find('li').eq(position));
        $this.prependTo($table);
    } else if ($this.data('position') != 0) {
        position = $this.data('position');
        $this.insertAfter($table.find('li').eq(position));                
    }
  });
});

Обратите внимание, что просто изменив соответствующие теги:

  • table на ul
  • tr до li
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...