index()是jQuery中的內置方法,用於返回指定元素相對於選擇器的索引。
用法:
$(selector).index(element)
參數:它接受可選參數“element”,該參數用於獲取元素的位置。
返回值:它返回一個整數,該整數表示指定元素的索引。
代碼1:
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
<!--jQuery code to demonstrate index function -->
// document ready
$(document).ready(function() {
// if the list is clicked
$("li").click(function() {
// index()
// to return the index of the clicked
// element of the list
document.getElementById("demo").innerHTML = "Clicked Index "
+ $(this).index();
});
});
</script>
</head>
<body>
<p>Click on the elements of the list to display their index
number with respect to the other elements in the list.</p>
<ul>
<li>Geeks</li>
<li>for</li>
<li>Geeks</li>
</ul>
<p id="demo"></p>
</body>
</html>
輸出:
在單擊列表上的任何元素之前
Click on the elements of the list to display their index number with respect to the other elements in the list.
- 極客
- 對於
- 極客
點擊“for”-
Click on the elements of the list to display their index number with respect with the other elements in the list.
- 極客
- 對於
- 極客
代碼2:
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>
<!--jQuery code to demonstrate index function -->
// document ready
$(document).ready(function() {
// if the list is clicked
$("li").click(function() {
// index()
// to return the index of the clicked
// element of the list
document.getElementById("demo").innerHTML = "Clicked Index "
+ $($(".myclass")).index($("#id"));
});
});
</script>
</head>
<body>
<p>Click on the elements of the list to display their index
number with respect with the other elements in the list.</p>
<ul>
<li>Geeks</li>
<li class="myclass">for</li>
<li class="myclass" id="id">Geeks</li>
</ul>
<p id="demo"></p>
</body>
</html>
輸出:
在單擊列表上的任何元素之前,
Click on the elements of the list to display their index number with respect with the other elements in the list.
- 極客
- 對於
- 極客
點擊列表中的任何元素後,
Click on the elements of the list to display their index number with respect with the other elements in the list.
- 極客
- 對於
- 極客
相關用法
- JQuery on()用法及代碼示例
- JQuery last()用法及代碼示例
- JQuery after()用法及代碼示例
- JQuery val()用法及代碼示例
- JQuery has()用法及代碼示例
- JQuery first()用法及代碼示例
- JQuery eq()用法及代碼示例
- JQuery one()用法及代碼示例
- JQuery animate()用法及代碼示例
- JQuery scrollTop()用法及代碼示例
- JQuery wrap()用法及代碼示例
- JQuery unwrap()用法及代碼示例
- JQuery not()用法及代碼示例
- JQuery clearQueue()用法及代碼示例
注:本文由純淨天空篩選整理自ShivamKD大神的英文原創作品 jQuery | index() with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。