请考虑以下html
<ul id="headmenu">
<li id="headmenuitem1"></li>
<li id="headmenuitem2"></li>
<li id="headmenuitem3"></li>
<li id="headmenuitem4"></li>
</ul>
我需要在一个项目上选择所有其他元素。
例如,我正在headmenuitem1
$(document).ready(function () {
$("#headmenuitem1").hover(function () { //When item is hovered...
$(this).... //(select all the other items)
})
});
执行this
时,我需要选择所有其他项目,因此在示例中,必须选择项目headmenuitem2, headmenuitem3 and headmenuitem4
有什么建议吗?感谢
答案 0 :(得分:13)
您有以下选择:
除this
以外的所有级别:
$(this).siblings();
包括this
在内的所有级别,使用.not(this)
排除this
:
$(this).parent().children();
立即在同一级别上:
$(this).prev();
紧接着在同一级别:
$(this).next();
所有以前在同一级别:
$(this).prevAll();
所有下一个在同一级别:
$(this).nextAll();
希望你能通过名字本身理解语法......
答案 1 :(得分:4)
$(document).ready(function () {
$("#headmenuitem1").hover(function () { //When item is hovered...
var $siblings = $(this).siblings(); //(select all the other items)
})
});
答案 2 :(得分:2)
回答你的问题:
$(document).ready(function () {
$("#headmenu1").hover(function () { //When item is hovered...
$(this).siblings()...;
})
});
你想要这适用于所有的李?如果是这样,您可以推广您的选择器。
$(document).ready(function () {
$("#headmenu li").hover(function () { //When item is hovered...
$(this).siblings()...;
})
});
答案 3 :(得分:2)
var headmenuitem1 = document.getElementById("headmenuitem1");
headmenuitem1.addEventListener("mouseover", hover);
headmenuitem1.addEventListener("mouseout", hover);
function hover() {
var nodes = [].slice.call(this.parentNode.children);
// remove current node
nodes.splice(nodes.indexOf(this), 1);
console.log(nodes);
}