简体   繁体   English

如何使用JavaScript(无框架)从列表中显示X个LI数?

[英]How do I show X number of LI from a list using javascript (no frameworks)?

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. 现在,导航栏上有一个下拉菜单,其中有14个选项。 The client wants to only show 3 of them. 客户只想显示其中3个。

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. 他们没有使用诸如jquery或mootools之类的任何框架,因此我必须以老式的方式进行此操作,但是,我已经陷入困境。

<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? 添加display:none到列表项4-14的JavaScript代码是什么?

(this also helps me get back to JS fundamentals and not relying on frameworks). (这也有助于我回到JS基础上,而不是依赖于框架)。

Thanks for your help! 谢谢你的帮助!

You can use CSS in JavaScript. 您可以在JavaScript中使用CSS。

Here is the reference: http://codepunk.hardwar.org.uk/css2js.htm 这是参考: http : //codepunk.hardwar.org.uk/css2js.htm

Plus, check out Mozilla JavaScript reference. 另外,请查看Mozilla JavaScript参考。

You can do a getElementById() to get the menu, then getElementsByTagName() for the LIs which will return an array (say items[]). 您可以执行getElementById()来获取菜单,然后对LIs进行getElementsByTagName()来返回数组(例如items [])。 And then change style for items[3] to items[13]. 然后将项目[3]的样式更改为项目[13]。

Edit 编辑

I made you a small code: 我给你做了一个小代码:

var menu = document.getElementById('mylist');
var LIs = menu.getElementsByTagName('li');
for(var i = 3; i< 14; i++)
    LIs[i].style.display='none';

Something like this? 像这样吗 (off the top of my head, sorry if it's sloppy) (从我的头顶上,抱歉,如果马虎)

var children= document.getElementByid("mylist").childNodes;
for (var i = 0; i < children.length; i++){
    if (i < 2) children[i].style.display = "none";
}

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 to none . 您必须获取列表的子节点,并将客户端不希望看到的每个节点的style.display属性设置为none 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 a tagName of "LI" before processing. 这听起来不太棘手,但是子节点集合可以包含元素,文本节点,注释等,因此在处理之前,您必须检查以确保该节点是tagName为“ LI”的元素。 Below is some code that should do the trick. 以下是一些应该可以解决问题的代码。

for (var node = document.getElementById('mylist').firstChild; node != null; node = node.nextSibling) {
   if (node.type === 1 && node.tagName.toUpperCase() === "LI") {
      if (/* node is not one of the ones your client wants to see */) {
         node.style.display = 'none';
      }
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM