如何使用 javascript(无框架)从列表中显示 X 数量的 LI?
我有一个由服务器填充的菜单,但我无法访问该服务器。所以我仅限于在客户端执行此操作。
现在导航上有一个下拉菜单,有 14 个选项。客户只想展示其中的 3 个。
他们没有使用任何像 jquery 或 mootools 这样的框架,所以我必须用老式的方式来做这件事,然而,我却陷入了困境。
选项 1
选项 2
选项 3
选项 4
等
将 display:none
添加到列表项 4-14 的 javascript 代码是什么?
(这也帮助我回到 JS 基础知识而不是依赖框架)。
感谢您的帮助!
I have a menu that is being populated by a server and I have no access to the server. So I am limited to doing this on the client side.
Right now there is a dropdown menu on the navigation with 14 choices. The client wants to only show 3 of them.
They're not using any frameworks like jquery or mootools, so I have to do this the old-fashioned way, yet, I'm at a wall.
<ul id='mylist'>
<li>option 1</li>
<li>option 2</li>
<li>option 3</li>
<li>option 4</li>
<li>etc</li>
</ul>
What's the javascript code to add display:none
to list items 4-14?
(this also helps me get back to JS fundamentals and not relying on frameworks).
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以执行
getElementById()
来获取菜单,然后执行getElementsByTagName()
来获取 LI,它将返回一个数组(例如 items[])。然后将 items[3] 的样式更改为 items[13]。
编辑
我给你写了一个小代码:
You can do a
getElementById()
to get the menu, thengetElementsByTagName()
for the LIs which will return an array (say items[]).And then change style for items[3] to items[13].
Edit
I made you a small code:
您可以在 JavaScript 中使用 CSS。
这是参考:http://codepunk.hardwar.org.uk/css2js.htm
另外,请查看 Mozilla JavaScript 参考。
You can use CSS in JavaScript.
Here is the reference: http://codepunk.hardwar.org.uk/css2js.htm
Plus, check out Mozilla JavaScript reference.
像这样的东西吗? (从我的头顶上下来,抱歉,如果马虎)
Something like this? (off the top of my head, sorry if it's sloppy)
您必须获取列表的子节点,并将客户端不希望看到的每个子节点的
style.display
属性设置为none
。这听起来不太棘手,但子节点集合可以包含元素、文本节点、注释等,因此您必须检查以确保该节点是具有tagName
的元素处理前的“LI”。下面是一些可以解决这个问题的代码。You'll have to grab the child nodes of the list and set the
style.display
property of each of the ones that your client doesn't want to see tonone
. This doesn't sound too tricky, but the child node collection can contain elements, text nodes, comments, etc, so you'll have to check to make sure that the node is an element with atagName
of "LI" before processing. Below is some code that should do the trick.