如何使用 JavaScript 计算 asp.bulletedlist 中的列表项数量

发布于 2024-08-25 03:03:03 字数 423 浏览 2 评论 0原文

我有一个 asp:bulletedlist 控件,它位于 div 标记内,我需要计算控件内的列表项的数量。搜索互联网,并注意到项目返回的 html 是一个列表,即

  • ,我想我可以使用以下示例:
  • var listcontrol = document.getElementById('BulletedList1');
    var countItems = listcontrol.getElementByTagName('li').length;
    

    但是,当我这样做时,它会抛出并错误表明此控件不存在对象。

    所以,我的问题是,因为我必须在客户端执行此操作,因为我想使用它来设置 div 标签的高度,所以如何使用 javascript 计算 asp:bulletedlist 控件内的项目数?

    I have an asp:bulletedlist control, which sits inside a div tag, and I need to count the number of list items inside the control. Searching the internet, and noting the fact the html given back by the items is a list i.e. <li>, I thought I could use an example of:

    var listcontrol = document.getElementById('BulletedList1');
    var countItems = listcontrol.getElementByTagName('li').length;
    

    However, when I do this, it throws and error saying that no object exists for this control.

    So, my problem is, and because I must do this clientside because I want to use this to set the height of the div tag, is how do you count the number of items inside a asp:bulletedlist control with javascript?

    如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

    扫码二维码加入Web技术交流群

    发布评论

    需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

    评论(1

    痴者 2024-09-01 03:03:03

    您不能像使用 document.getElementById 那样使用它,因为呈现时 Asp.Net 控件的实际 ID 与您在控件上设置的 ID 不同。查看页面的源代码,您将看到实际的 ID 是什么。然后,如果您愿意,您可以使用它,并且此代码应该可以工作,但如果您移动了项目符号列表控件,它就会中断,因为层次结构会发生变化。

    另一种方法是使用 jQuery。在您的示例中,您可以这样做:

    $('[id$=BulletedList1]').children('li').size()
    

    这将选择以“BulletedList1”结尾的元素,获取 li 子元素,然后返回集合的大小。

    You can't use document.getElementById like you are using it because the actual ID for an Asp.Net control when rendered is different than what you set for the ID on the control. View the source of your page and you will see what the actual ID is. You can then use that if you want and this code should work, but it would break if you ever moved the bulletedlist control, since the hierarchy would change.

    Another way to do this would be to use jQuery. In your example, you could do this:

    $('[id$=BulletedList1]').children('li').size()
    

    This would select the element that ends with 'BulletedList1', gets the li children, and then returns the size of the collection.

    ~没有更多了~
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文