Home > Web Front-end > Front-end Q&A > Set index through jquery

Set index through jquery

WBOY
Release: 2023-05-18 12:13:07
Original
644 people have browsed it

Set index through jquery

In web development, it is often necessary to obtain or set the position of an element among sibling elements, which requires the use of index. jQuery provides a very convenient method to get or set the index of an element.

1. Get the index of the element

For example, in the following code structure, we need to get the index of the li element:

<ul>
  <li>第一个</li>
  <li>第二个</li>
  <li>第三个</li>
</ul>
Copy after login

It is very simple to use jQuery to get the index, just need Just use the index() method:

$("li").click(function(){
  var index = $(this).index();
  alert(index);
});
Copy after login

The meaning of this code is: when the li element is clicked, get its position in the sibling element and alert it.

2. Set the index of an element

Sometimes, you need to dynamically change the position of an element among sibling elements. For example, the current position of the li element is 2, and I want to change it to 1.

<ul>
  <li>第一个</li>
  <li>第三个</li>
  <li>第二个</li>
</ul>
Copy after login

At this time, you can use the after() or before() method provided by jQuery to achieve:

$("li:eq(2)").after($("li:eq(0)"));
Copy after login

The meaning of this code is: put the element with index 2 (the third ) moves to the front of the element with index 0 (the first one), that is, the position becomes 1.

In addition to using the after() or before() method, you can also use the appendTo() or prependTo() method. For example, I want to move the third li element to the front:

$("li:eq(2)").prependTo($("ul"));
Copy after login

This code means: add the element with index 2 (the third) to the ul, but put it at the front , that is, the position becomes 0.

Summary:

You can easily get or set the position of an element through jQuery. Choosing the appropriate method according to your needs can better realize the function.

The above is the detailed content of Set index through jquery. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template