jquery:按属性查找第一个元素
我在网页的左侧有一个包含类别的列表,在右侧有一个包含项目的列表。 带有项目的列表具有名为cat的属性,值为数字。
单击该类别应该滚动到具有相同categoryid的第一个项目。
有小费吗? 🙂
这是html:
asp:Repeater runat="server" ID="repCategory" OnItemDataBound="CategoryItemRepeater">
代码隐藏:
所属分类:
var lbl = (HtmlGenericControl)e.Item.FindControl("catItem"); lbl.Attributes.Add("catId",""+rest.CategoryId);
ITEMLIST:
var menuItem = (HtmlGenericControl)e.Item.FindControl("menuItem"); menuItem.Attributes.Add ("cat","cat"+item.Item.Category.FirstOrDefault().CategoryId);
jQuery的:
$('.menuListUl li div').bind('click', function () { var catId = $(this).attr('catid'); //The categoryid on the element clicked. // Now: find the first element with the same cat id var element = ""; The element found. $('html, body').animate({ scrollTop: element.offset().top }, 2000); });
这将选择’foobar’作为catid的元素。 这似乎是你想要的吗?
$('.menuListUl li div[catid="foobar"]')