提问人:Steve Perks 提问时间:11/4/2008 更新时间:11/4/2008 访问量:387
点击第n个项目后,如何操作另一个第n个元素?
After clicking the nth item, how do I manipulate another nth element?
问:
我正在使用 jQuery,并希望在单击第 n 个链接后定位列表中的第 n 个 <li>。
<ul id="targetedArea">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div id="clickedItems">
<a></a>
<a></a>
<a></a>
<a></a>
</div>
我可以单独定位它们,但我知道必须有一种更快的方法,通过传递我单击的 <a> 元素。
$("#clickedItem a:eq(2)").click(function() {
$("#targetedArea:eq(2)").addClass('active');
return false;
});
干杯,
史蒂夫
答:
4赞
Owen
11/4/2008
#1
像这样的东西怎么样:
$('#clickedItems a').click(function() {
// figure out what position this element is in
var n = $('#clickedItems a').index($(this) );
// update the targetedArea
$('#targetedArea li:eq('+n+')').html('updated!');
return false;
});
假设 U 和 Elements 之间有 1:1 的关系,它将更新相应的<a>
<li>
<li>
1赞
Tomalak
11/4/2008
#2
我知道这并没有直接回答你的问题,但也许你让它变得比实际更难。
为每个 A 和 LI 元素指定一个 ID,并创建这些 ID,以便您可以相互推断它们。只要点击一个 A,您就会立即知道 LI 的 ID,并可以直接引用它。
作为副作用,这比任何可能做同样事情的聪明的jQuery更有效。
0赞
ken
11/4/2008
#3
我不知道jQuery在mootools中是否有这样的东西
$$('a.clickedItems').addEvent('click', function(e){
e.preventDefault();
$('targetedArea').getChildren()[this.getAllPrevious().length].addClass('selected');
});
0赞
nickf
11/4/2008
#4
$('#clickedItems a').click(function() {
// you probably want to turn off the currently active one
$('#targetedArea li.active').removeClass("active");
// count the links previous to this one and make the corresponding li active
$('#targetedArea li:eq(' + $(this).prevAll('a').length + ')').addClass("active");
// prevent the browser from going to the link
return false;
});
评论