在我的网页上,我想要“隐藏”或“取消隐藏”几个已经在DIV元素中的元素(在本例中是C和F),例如:
<div> Select A or B <span name='hide' > or C</span></div>
<div> Also select D or E <span name='hide' > or F</span></div>
(etc)我使用javascript在页面打开时隐藏所有“隐藏”元素,除了在localhost上打开页面时,所有元素都会显示出来。我不一定知道有多少个‘隐藏’元素(动态生成)。
var hids=document.getElementsByName('hide');
if(hids!=null) {
for(var j=0; j< hids.length; j++) {
if(localhost==true) { // only if on localhost
hids[j].style.visibility='visible';
}
else hids[j].style.visibility='hidden';
}
}但是,'name‘属性对于SPAN无效。当我使用DIV而不是SPAN时,它会弄乱格式。我应该如何正确地解决这个问题?
发布于 2018-02-03 01:10:48
使用class而不是name
<span class="my-class"> or C</span>和getElementsByClassName而不是getElementsByName
document.getElementsByClassName("my-class");发布于 2018-02-03 01:10:49
如果span没有name属性,请尝试使用class name
var hids=document.getElementsByClassName('hide');并将您的html更改为
<div> Select A or B <span class='hide' > or C</span></div>
<div> Also select D or E <span class='hide' > or F</span></div>发布于 2018-02-03 01:12:30
您可以使用querySelectorAll按className hide查找
var localhost = false;
var hids = document.querySelectorAll('.hide');
if (hids != null) {
for (var j = 0; j < hids.length; j++) {
if (localhost) { // only if on localhost
hids[j].style.visibility = 'visible';
} else hids[j].style.visibility = 'hidden';
}
}<div> Select A or B <span class='hide'> or C</span></div>
<div> Also select D or E <span class='hide'> or F</span></div>
(etc)
资源
https://stackoverflow.com/questions/48587581
复制相似问题