简体   繁体   English

如何设置未知数量的ID?

[英]How can I set an unknown number of IDs?

I have the following code which loops through an array of an unknown length. 我有以下代码循环遍历一个未知长度的数组。 I want to change the style of one of the paragraphs by JavaScript HTML DOM, and want to change it on one single paragraph. 我想通过JavaScript HTML DOM更改段落之一的样式,并希望在一个段落上对其进行更改。 Right now the class name is demo2 but I want to set it to something like demo_x. 现在,类名是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";
        }
    }

Use the for loop to set class each, like this: 使用for循环分别设置类,如下所示:

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


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

Output: 输出:

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

I've understood your question. 我了解您的问题。

You should use the "this" keyword: when the function is called by the onclick, you'll bring the whole DOM element where the "onclick" has been performed as "this". 您应该使用“ this”关键字:当onclick调用该函数时,会将在其中执行了“ onclick”的整个DOM元素带为“ this”。

In a nutshell: 简而言之:

function toggleFunction() {

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

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

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