簡體   English   中英

如何在JavaScript中獲取數組的第n個元素?

[英]How to get the nth element of an array in javascript?

假設我在HTML代碼中插入了以下JavaScripts ...

<a href="http://example.com" data-example="my example">Example #1</a>
<script src="http://example.com/javascript.js"></script>

<a href="http://example.com" data-example="my example">Example #2</a>
<script src="http://example.com/javascript.js"></script>

<a href="http://example.com" data-example="my example">Example #3</a>
<script src="http://example.com/javascript.js"></script>

如何在第三個鏈接中獲取數據示例的值(示例3)?

使用eq() Reduce the set of matched elements to the one at the specified index.

$('a[data-example]').eq(2).text();

小提琴

嘗試這個:

var data = $('a:eq(2)').data('example');

:eq

您也可以使用psuedo選擇器 DEMO

$('a:nth-of-type(3)').data('example')

我建議您不要依賴“ 獲取所有具有data-example的錨點 ”,而應做得更明確一些,例如為這些鏈接指定一個class

<a class="my-link" href="http://example.com" data-example="my example">Example #1</a>
<script src="http://example.com/javascript.js"></script>

<a class="my-link" href="http://example.com" data-example="my example">Example #2</a>
<script src="http://example.com/javascript.js"></script>

<a class="my-link" href="http://example.com" data-example="my example">Example #3</a>
<script src="http://example.com/javascript.js"></script>

然后,使用jQuery

 $(".my-link:eq(3)").data("example")

為什么提出建議? 因為您以后可能還會有其他帶有data-example鏈接

如果要顯示data-example屬性的值,可以在CSS中使用:before:after偽類。

a:before {
    content: attr(data-example);
}

工作小提琴

在此,通常可以使用的功能。

function getEqData(selector, data, num){
    return $(selector).eq(num-1).data(data);
}

var data = getEqData('a', 'example', 3);
console.log(data);

的jsfiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM