前端页面拥有多个形同id获取并全部处理
<span id="tmpHidePop" class="layerpop_closed" onclick="hidePopup()">收起<i></i></span>
document.getElementByID("id")只能获取此id第一条对象,若有多个,其他数据属性都是null.
所以,退而求其次,怎样获取呢?
通过name属性:
<span id="tmpHidePop" name = "tmpHidePopName" class="layerpop_closed" onclick="hidePopup()">收起<i></i></span>
var titleArr = document.getElementsByName("tmpHidePopName"); console.log(titleArr); for (var i = 0; i <titleArr.length ; i++) { titleArr[i].click(); }
还有一种方法,通过TagName(),然后进行层级筛选,定位到我们需要的具体对象
<div id="yrPop" data-hide="true" data-closecallback="undefined" class="layerpop" style="top: 62px; height: 347px; display: block;"> <span id="tmpHidePop" name="tmpHidePopName" class="layerpop_closed" onclick="hidePopup()">收起<i></i></span> </div> <div id="yrPop" data-hide="true" data-closecallback="undefined" class="layerpop" style="top: 62px; height: 347px; display: block;"> <span id="tmpHidePop" name="tmpHidePopName" class="layerpop_closed" onclick="hidePopup()">收起<i></i></span> </div> <div id="yrPop" data-hide="true" data-closecallback="undefined" class="layerpop" style="top: 62px; height: 347px; display: block;"> <span id="tmpHidePop" name="tmpHidePopName1" class="layerpop_closed" onclick="hidePopup()">收起<i></i></span> </div> <div id="yrPop" data-hide="true" data-closecallback="undefined" class="layerpop" style="top: 62px; height: 347px; display: block;"> <span id="tmpHidePop" name="tmpHidePopName" class="layerpop_closed" onclick="hidePopup()">收起<i></i></span> </div>
var divArr = document.documentElement.getElementsByTagName("div");
for (var i = 0; i <divArr.length ; i++) {
if(divArr[i].name=="tmpHidePopName"){
divArr[i].click();
}
}
当然,这里面代码逻辑不严谨,借鉴的同志要注意一下,还需要补充判断。
我不是来改变世界的