我有一个隐藏/显示的切换按钮,并显示在每篇文章上。 (我的网站有大约一百万篇文章)
但是在每个网站上,切换按钮仅切换第一篇/顶级文章。
HTML:
<button class="proddetBtn" style="vertical-align:middle" onclick="myFunction()"><div>Show productdetails</div>
</button>
<div id="myCRITERIA" style="display: ">
<?php echo $criteria ?>
</div> <br>
JS:
function myFunction() {
var x = document.getElementById('myCRITERIA');
if (x.style.display === 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
答案 0 :(得分:0)
在函数中传递targeted element Id
。然后使用三元运算符应用切换效果
function myFunction(id) {
var x = document.getElementById(id);
x.style.display = x.style.display === 'none'? 'block' :'none';
}
<button class="proddetBtn" style="vertical-align:middle" onclick="myFunction('myCRITERIA')"><div>Show productdetails</div>
</button>
<div id="myCRITERIA" style="display: ">
some
<?php echo $criteria ?>
</div> <br>
<强>更新强>
或者可以在课堂上使用更多数量的元素。ForEach
用于迭代元素
function myFunction() {
document.querySelectorAll('.clear').forEach(function(a) {
a.style.display = a.style.display === 'none' ? 'block' : 'none';
})
}
<button class="proddetBtn" style="vertical-align:middle" onclick="myFunction()"><div>Show productdetails</div>
</button>
<div class="clear" style="display:none">some</div> <br>
<div class="clear" style="display:none ">some</div> <br>
<div class="clear" style="display: ">some</div> <br>
<div class="clear" style="display:none ">some</div> <br>
<div class="clear" style="display: ">some</div> <br>
<div class="clear" style="display:none ">some</div> <br>
<div class="clear" style="display: ">some</div> <br>