如何设置未知数量的ID



我有下面的代码,它在未知长度的数组中循环。我想通过JavaScriptHTMLDOM更改其中一个段落的样式,并想在一个单个段落上更改它。现在类名是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";
}
}

使用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>

我理解你的问题。

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

简而言之:

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

最新更新