我有这样的HTML代码:
<div>
<a>Link A1</a>
<a>Link A2</a>
<a>Link A3</a>
</div>
<div>
<a>Link B1</a>
<a>Link B2</a>
<a>Link B3</a>
</div>
Run Code Online (Sandbox Code Playgroud)
当用户从上面的HTML中单击链接时,我想获取相应<a>
元素的jQuery对象,然后操纵它的兄弟.除了为每个<a>
元素创建一个ID ,并将该ID传递给onclick事件处理程序之外,我想不出任何其他方法.我真的不想使用ID.
有什么建议?
Sho*_*og9 69
幸运的是,jQuery选择器允许您更自由:
$("div a").click( function(event)
{
var clicked = $(this); // jQuery wrapper for clicked element
// ... click-specific code goes here ...
});
Run Code Online (Sandbox Code Playgroud)
...将指定的回调附加到<a>
a中包含的每个回调<div>
.
当jQuery单击事件调用您的事件处理程序时,它会将"this"设置为单击的对象.要将其转换为jQuery对象,只需将其传递给"$"函数:$(this)
.因此,要获得下一个兄弟元素,您可以在单击处理程序中执行此操作:
var nextSibling = $(this).next();
Run Code Online (Sandbox Code Playgroud)
编辑:在看完凯文的评论后,我意识到我可能会误解你的想法.如果你想做他要求的事情,即选择另一个div中的相应链接,你可以$(this).index()
用来获得点击链接的位置.然后,您可以通过其位置选择另一个div中的链接,例如使用"eq"方法.
var $clicked = $(this);
var linkIndex = $clicked.index();
$clicked.parent().next().children().eq(linkIndex);
Run Code Online (Sandbox Code Playgroud)
如果您希望能够双向进行,则需要某种方法来确定您所在的div,以便在"parent()"之后需要"next()"或"prev()"
你会发现siblings()和parent()方法在这里很有用.
// assuming A1 is clicked
$('div a').click(function(e) {
$(this); // A1
$(this).parent(); // the div containing A1
$(this).siblings(); // A2 and A3
});
Run Code Online (Sandbox Code Playgroud)
将这些方法与andSelf()组合将允许您操纵所需元素的任意组合.
编辑:Mark留下的关于Shog9答案的事件授权的评论非常好.在jQuery中完成此操作的最简单方法是使用live()方法.
// assuming A1 is clicked
$('div a').live('click', function(e) {
$(this); // A1
$(this).parent(); // the div containing A1
$(this).siblings(); // A2 and A3
});
Run Code Online (Sandbox Code Playgroud)
我认为它实际上将事件绑定到根元素,但效果是一样的.它不仅更灵活,而且在很多情况下也提高了性能.请务必阅读文档以避免任何问题.