如何将列表项移到第一个位置然后移回?

时间:2019-10-14 16:25:50

标签: javascript jquery html

我正在尝试使此代码适合我的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));
        }
    });

});

我下面的代码适用于表格,但我想一一实现。 有没有办法使复选框输入成为li或锚标记?

Demo

3 个答案:

答案 0 :(得分:1)

在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));                
    }
  });
});

请注意,只需更改相应的标签:

  • ul
  • tr li

答案 1 :(得分:1)

如果您不想使用复选框,而是使用简单的标签,请参见以下示例:

请参见JSFiddler:http://jsfiddle.net/nfywg06b/5/

我没有重命名变量,因此很容易理解重要的调整。

使用// helper functions const el = ( query, context = document ) => context.querySelector( query ), elementExists = query => Boolean( el( query ) ), ifElementExists = ( query, fn = () => undefined ) => elementExists( query ) && fn(), elStyle = query => ( prop, value ) => el( query ).style[ prop ] = value, changeStyle = query => ( prop, value ) => () => elStyle( query )( prop, value ); // execution ifElementExists( "#category .st_banner_row", changeStyle( "#search_filters_wrapper" )( "margin-top", "40px" ) );变量定义行为:发送到最后一个职位或更改职位(旧版行为)

jQuery:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='category'>
  <span>Below is 40px</span>
  <div id="search_filters_wrapper">
    Filter
  </div>
  <div class="st_banner_row" style="">
    There is Banner
  </div>
</div>

HTML:

${ARRAY[index]}

CSS:

goToLast

答案 2 :(得分:1)

根据您的示例,我假设您无法控制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>