Jquery获取列表项的父元素单击



我想写一个简单的悬停函数(请不要建议另一个,我有特定的需求)。我有悬停工作,使它将显示到列表项的权利,它是悬停。页面的样式显示了左侧导航,其中ul背景看起来像一个实体块。这意味着我需要我的悬停在整个ul的右边,而不仅仅是我的li,如果它是短的。我试图得到的父li,但我得到一个错误。Parent不是一个函数。我如何获得一个li的父元素,这样我就可以得到它的位置。

my li有一个类。left-nav-item

this.myhover = function () {
this.xOffset = -10; // x distance from mouse
this.yOffset = 10; // y distance from mouse       
$(".left-nav-item").unbind().hover(
function (e) {
this.top = (e.pageY + yOffset);
this.left = (e.pageX + xOffset);
alert(this.title);
this.parent().css('background-color', 'red');
$('body').append('<p id="new">My Hover Text</p>');
$('p#new').css("top", this.top + "px").css("left", this.left + "px").css("position", "absolute").fadeIn("slow");
},
function () {
//$("p#new").fadeOut("slow").remove();
}
).mousemove(
function (e) {
this.top = (e.pageY + yOffset);
this.left = (e.pageX + xOffset);
//$("p#new").css("top", this.top + "px").css("left", this.left + "px");
}
);
};
jQuery(document).ready(function ($) { myhover(); });

你的问题:

我如何得到一个li的父元素,这样我就可以得到它的位置。

$('your li').closest('ul');

Try -

$(this).parent().css('background-color', 'red');

parent()是一个jQuery函数,只对jQuery包装元素起作用。

$('li.left-nav-item').parent();

最新更新