简体   繁体   English

使用javascript将样式应用于某些列表项

[英]Using javascript to apply styles to certain list items

I have been trying to learn JavaScript and trying to crack a JS Fiddle to try out. 我一直在努力学习JavaScript并尝试破解JS小提琴试试。 http://jsfiddle.net/Xy9Ga/ Objectives Using JAVASCRIPT : 1) Make every third list item red text and italic, starting with first item. http://jsfiddle.net/Xy9Ga/使用JAVASCRIPT的目标:1)从第一项开始,使每三个列表项成为红色文本和斜体。 2)Make every tenth item bold and underlined, starting at fifth item. 2)从第五项开始,将每个第十项加粗并加下划线。

I know to create the css classes and then apply them to the list items accordingly. 我知道要创建css类,然后相应地将它们应用于列表项。 I am having trouble trying to figure out the JavaScript side of things :( Not really looking for someone to code it for me but possibly explain the logic on how to do it. I don't know where to start 我无法弄清楚JavaScript方面的问题:(不是真的在找人为我编码,但可能会解释如何做到这一点的逻辑。我不知道从哪里开始

document.load =function() {
};

The two CSS classes I made are 我制作的两个CSS类是

    .reditem {
    color: red;
    font-style: italic;
}

.blackitem {
    font-weight: bold;
    font-style: underline;
}

Use the nth-child pseudo-class instead. 请改用nth-child伪类。

I updated your fiddle to show this. 我更新你的小提琴来表明这一点。

Basically, the coefficient is how often it is applied, and the part added is where it starts (that's not exactly right, but it's close enough for me). 基本上,系数是应用的频率,添加的部分是它开始的地方(这不完全正确,但对我来说足够接近)。

That means for every third, starting at the first, it's nth-child(3n+1) , and for every tenth, starting at the fifth, it's nth-child(10n+5) . 这意味着每三分之一,从第一个开始,它是nth-child(3n+1) ,并且从第五个开始每十分之一,它是nth-child(10n+5)

Here is the documentation for nth-child . nth-child的文档。

Created a fork of your fiddle and what I believe you're asking, take a peek if you get stuck! 创造了你的小提琴的叉子和我相信你的要求,如果你卡住了就看一眼! jsfiddle.net/realchaseadams/Xy9Ga/8 jsfiddle.net/realchaseadams/Xy9Ga/8

var list_items = document.getElementsByTagName('li');

for(var i = 0, len = list_items.length; i < len; i++) {
    if (i % 3 === 0) {
      list_items[i].className += ' third';   
    }
    if ((i % 10 === 0 && i !== 0) || i === 4) {
      list_items[i].className += ' fifth';   
    }
}

It looks like you're more interested in control flow & operators and adding classes that have properties defined in styles. 看起来您对控制流和运算符更感兴趣,并添加具有样式定义属性的类。

What you need to do is. 你需要做的是。

  1. Create a Nodelist first with your all li elements in it. 首先创建一个Node列表,其中包含所有li元素。
  2. Traverse the whole list and check whether the index is divisble by 3 or not. 遍历整个列表并检查索引是否可以除以3。
  3. When you got your element change the color of text by using css() function. 当你的元素通过使用css()函数更改文本的颜色。

     var nodeList = $('li'); nodeList.each(function (index, val) { if ((index + 1) % 3 === 0) { $(this).css('color', 'red'); } }); 

Here is your fiddle modified 这是你的小提琴修改

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

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