jquery函数中的索引意味着什么
我是一个jQuery开始所以,如果它不是很好的质量原谅我。
我想知道index
在函数中的含义以及它究竟指的是什么。 以前我认为它指的是像0,1,2,3等索引号,但当我通过1,2,3代替索引时,我的代码停止工作。 我检查了它的类型,它显示了我的number
数据类型。 现在让我告诉我究竟是什么错误以及jQuery中的索引和元素的概念,因为大多数地方我发现这样的事情 –
function(e){ }
我的工作代码 –
Example $(document).ready(function(){ $( 'li' ).html(function( index, oldHtml ) { //alert(typeof($(this).index())); return oldHtml + '!!!' }); }); - This is List item 1
- This is List item 2
- This is List item 3
- This is List item 4
- This is List item 5
我的尝试 –
$( 'li' ).html(function( 3, oldHtml ) {.... $( 'li' ).html(function( "3", oldHtml ) {.... $( 'li' ).eq(3).html(function( "3", oldHtml ) {......
index
参数表示匹配集合中元素的索引。 你不应该将值传递给它。 它是一个传递给匿名函数的参数,你可以在里面使用它来确切地知道在需要时调用这个匿名函数的元素:
$( 'li' ).html(function( index, oldHtml ) { return 'new html ' + index; });
索引基于零,因此结果将是:
new html 0 new html 1 new html 2 new html 3 new html 4
index表示指向由jquery选择的某个元素的位置的数字。
例如,所选元素是$('#haha')
- 1
- 2
- 3
所以第一个li
是索引0,然后是1,依此类推
在根据集合查看数据时,您可以使用index()。 例如
- foo
- bar
- baz
var listItem = document.getElementById('bar'); alert('Index: ' + $('li').index(listItem));
会给你li列表范围内的条形项的索引
请参阅jquery 文档
描述:从匹配的元素中搜索给定元素。
索引是元素的顺序,它将告诉您该元素具有哪个索引。 第一个将具有索引0,依此类推,在许多编程语言中非常常见,jQuery为您提供此工具。
首先, function(
是一个JavaScript语法错误。 其次,jQuery负责传递index参数的值,而不是你。 您的代码可能如下所示:
$('li').html(function(i, oldHtml) { return i === 0 ? "First LI" : (oldHtml + '!!!'); });
jQuery创建一个返回元素的数组,这是索引引用的元素集合 。 如果你返回typeof
,它将逻辑上返回数字,因为它是一个数字。
jsBin演示
$( '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+ '
My HTML: '+ html + '!!!'; });