2012-09-17 25 views
3

我是一個jQuery的開始,所以如果它質量不好,請原諒我。jquery函數中的索引是什麼意思

我想知道index在函數中意味着什麼,以及它究竟指的是什麼。以前我認爲它是指像索引號碼0,1,2,3等,但當我通過1,2,3代替索引我的代碼停止工作。我檢查了這種類型,它顯示我number數據類型。 現在讓我究竟是什麼即時通訊做錯了,指數和元素在jQuery中的大多數地方,我發現像這樣的概念 -

function(e){ 
} 

我的工作代碼 -

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Example</title> 
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script> 
<script type="text/javascript"> 
$(document).ready(function(){ 
$('li').html(function(index, oldHtml) { 
//alert(typeof($(this).index())); 
    return oldHtml + '!!!' 
}); 
}); 
</script> 
</head> 
<body> 

<ul> 
<li>This is List item 1</li> 
<li>This is List item 2</li> 
<li>This is List item 3</li> 
<li>This is List item 4</li> 
<li>This is List item 5</li> 
</ul> 

</body> 
</html> 

我嘗試 - -

$('li').html(function(3, oldHtml) {.... 

$('li').html(function("3", oldHtml) {.... 

$('li').eq(3).html(function("3", oldHtml) {...... 

回答

3

index參數表示匹配集合中元素的索引。你不應該把價值傳遞給它。這是傳遞到你可以使用裏面確切地知道哪個元素,如果你需要被調用這個匿名函數匿名函數的參數:

$('li').html(function(index, oldHtml) { 
    return 'new html ' + index; 
}); 

該指數是從零開始,因此結果會是:

<li>new html 0</li> 
<li>new html 1</li> 
<li>new html 2</li> 
<li>new html 3</li> 
<li>new html 4</li> 
+0

Thx對於一個非常簡單和簡明的解釋。我喜歡這個地方..真的是一個程序員的天堂...只是一點幫助..可以提供一個初學者的參考,因爲jQuery文檔似乎不大開始:) – Trialcoder

+1

我會建議你通過入門教程jQuery網站本身。一旦你習慣了基本的概念,就可以使用API​​參考。 –

1

索引意味着指向由jquery的選定某一元件的位置的數目..

例如所選擇的元件是$('#haha')

<ul id='haha'> 
<li>1</li> 
<li>2</li> 
<li>3</li> 
</ul> 

所以第一li是指數0,則1等等

0

你利用指數()在收集方面的數據看時。例如

<ul> 
    <li id="foo">foo</li> 
    <li id="bar">bar</li> 
    <li id="baz">baz</li> 
</ul> 


var listItem = document.getElementById('bar'); 
alert('Index: ' + $('li').index(listItem)); 

會給你的欄項目的索引李清單範圍

見jQuery的documentation

0

jQuery的創建您返回元素的數組,一個元素集合索引引用。如果你退回typeof它將邏輯上返回號碼,因爲它是一個數字。

jsBin demo

$('li').html(function(index, html) { 

    if(index===2){  // zero based, so it will colour the 3rd element! 
     $(this).css({color:'red'}); 
    } 

    return 'jQuery indexes me inside an array as n:'+ index+ 
      '<br> My HTML: '+ html + '!!!'; 

    }); 
0

描述:搜索從匹配的元素中的給定元素。

索引是元素的順序,它會告訴你這個元素具有哪個索引。第一個將有索引0等,在許多編程語言中很常見,jQuery爲你提供了這個工具。

0

首先,function(<some constant>)是一個JavaScript語法錯誤。其次,jQuery負責爲索引參數傳遞一個值,而不是你。您的代碼可能如下所示:

$('li').html(function(i, oldHtml) { 
    return i === 0 ? "First LI" : (oldHtml + '!!!'); 
}); 
相關問題