jquery: Find first element by attribute

2019-08-27 16:38发布

I have a list with categories on my left side on the webpage, and a list with items on the right side. The list with items have an attribute called cat, and the values are numbers.

Clicking on the category should scroll me to the first item with the same categoryid.

Any tips? :)

Here is the html:

asp:Repeater runat="server" ID="repCategory" OnItemDataBound="CategoryItemRepeater">
            <HeaderTemplate>
                <ul class="menuListUl">
            </HeaderTemplate>
            <ItemTemplate>
                <li>
                    <div id="catItem" runat="server"></div>
                </li>
            </ItemTemplate>
            <FooterTemplate></ul></FooterTemplate>
        </asp:Repeater>


 <div id="menuList">
            <asp:Repeater runat="server" ID="repFooditems" OnItemDataBound="MenuItemRepeater">
                <ItemTemplate>
                    <div class="menuItem" id="menuItem" runat="server">
                        <div runat="server" class="itemNumber" id="ItemId"></div>
                        <div runat="server" class="itemName" id="itemName"></div>
                        <div runat="server" class="itemDescription" id="itemDescriptionLbl"></div>
                    </div>
                </ItemTemplate>
            </asp:Repeater>

        </div>

Codebehind:

Categorylist:

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);
        });

1条回答
在下西门庆
2楼-- · 2019-08-27 17:10

This will select you the elements with 'foobar' as the catid. It seems to be this what you want right?

$('.menuListUl li div[catid="foobar"]')
查看更多
登录 后发表回答