如何设置未知数量的ID?

时间:2018-07-18 09:47:23

标签: javascript pug

我有以下代码循环遍历一个未知长度的数组。我想通过JavaScript HTML DOM更改段落之一的样式,并想在一个单个段落上对其进行更改。现在,类名是demo2,但是我想将其设置为demo_x之类的。

-for (x in c){
  tr
    td.icon
      .div
        img(src=c[x].companyLogo, width= '45px',style=' max-height=45px;')
      .div(style='padding-left:10px;')
        a(style='font-weight: 550; display:block;')=c[x].companyName
        a(style='display:block;')=c[x].companyDomain
    td
      span.demo1
      span.demo2
      span.less(style= 'color: #1d8bea;',onclick="toggleFunction()")
    //This script evaluates the array length, divides it into two arrays, and also does the show more/less effect.
    include ../public/javascripts/slice.pug
    td
      p(style='display: inline; color: #6e6e6e;') #{c[x].location.CountryCode}
      span , 
      a(style='display: inline;') #{c[x].location.State}
      span , 
      a(style='display: inline;') #{c[x].location.City}
    td
      p(style='color: #6e6e6e;') #{e[x]}
    td
      a  #{d[x]}
-}
script.
    function toggleFunction() {
        var t = document.getElementsByClassName("demo2");
        if (t.style.display === "none") {
            t.style.display = "inline";
        } else {
            t.style.display = "inline";
        }
    }

2 个答案:

答案 0 :(得分:0)

使用for循环分别设置类,如下所示:

- var c =  ['a', 'b', 'c'];


- for (var i = 0; i < c.length; i++) {
    div(class='row-'+c[i])
- }

输出:

<div class="row-a"></div>
<div class="row-b"></div>
<div class="row-c"></div>

答案 1 :(得分:0)

我了解你的问题。

您应该使用“ this”关键字:当onclick调用该函数时,将把执行“ onclick”的整个DOM元素带为“ this”。

简而言之:

function toggleFunction() {

        if (this.style.display === "none") {
            this.style.display = "inline";
        } else {
            this.style.display = "inline";
        }
    }