读书人

jquery新手有关问题 jquery index()

发布时间: 2013-08-01 15:23:18 作者: rapoo

jquery新手问题 jquery index()用法问题
关于jquery中index()函数的问题

<body>
<table>
<thead>
<tr>
<th colspan="2">鼠标点击表格项就可以编辑</th>
</tr>
</thead>
<tbody>
<tr>
<th>学号</th>
<th>姓名</th>
</tr>
<tr>
<td id="id">000001</td>
<td id="name">张三</td>
</tr>
<tr>
<td id="id">000002</td>
<td id="name">李四</td>
</tr>
<tr>
<td id="id">000003</td>
<td id="name">王五</td>
</tr>
<tr>
<td>000004</td>
<td>赵六</td>
</tr>
</tbody>
</table>
<input id="btnSave" type="button" value="确定">
</body>


页面很简单,就一个table

然后,点击提交的时候
$("#btnSave").click(function(){//按钮点击事件
var str = "";
var users = new Array();

$("table tbody tr").each(function(){
var tr = $(this);
var u = new User();
tr.find("td").each(function(){
var td = $(this);
var att = td.attr("id");
var value = td.html();

alert($(this).index());

if(att=="id") {
str = str + "{\"" + att +"\":\""+value +"\",";
u.id =value;
}

if(att=="name") {
str = str + "\""+att +"\":\""+value +"\" }";
u.name = value;
}


});
if(u.id!="") {
users.push(u);
}

});
str = "{\"users\":[" +str+"]}";

});


function User(id,name) {


this.id = id;
this.name = name;
return this;

}

关键是上条红色的代码,我想找出当前td在当前tr中的索引位置,可是每次都是返回-1

$(this).index();不是返回当前元素在同辈元素中的位置的吗?我这样写为什么不对?

我应该怎么写呢? jQuery index()
[解决办法]

引用:
返回-1,不是指在同辈元素中不存在吗?

是,我理解的不够全面:
If we omit the argument, .index() will return the position of the first element within the set of matched elements in relation to its siblings:

上面的引用出自:http://api.jquery.com/index/
[解决办法]
你要返回的是tr的索引, 而你当前所在的位置触发的是第一个td

你应该是$(this).parent("tr").index() 这样才可以。
[解决办法]
我运行了你的代码,没有问题,程序是正常的。
另外,jQuery的each方法会返回索引给你的,不用自己去调用index.


$("tr").each(function(index,elem){
//this === elem
});

$.each(obj,function(key,value){})
$.each(array,function(index,elem){});

读书人网 >JavaScript

热点推荐