如何使用 JavaScript 计算 asp.bulletedlist 中的列表项数量
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不能像使用 document.getElementById 那样使用它,因为呈现时 Asp.Net 控件的实际 ID 与您在控件上设置的 ID 不同。查看页面的源代码,您将看到实际的 ID 是什么。然后,如果您愿意,您可以使用它,并且此代码应该可以工作,但如果您移动了项目符号列表控件,它就会中断,因为层次结构会发生变化。
另一种方法是使用 jQuery。在您的示例中,您可以这样做:
这将选择以“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:
This would select the element that ends with 'BulletedList1', gets the li children, and then returns the size of the collection.