Javascript for…in seems to only return every other index in array [duplicate]

一世执手 提交于 2019-12-11 08:15:58

问题


I have a page (actually, about thirty or so) where I'm trying to change the classname of specific elements based on a querystring variable. Everything works fine except for this part, I'm getting a really weird result...

        var hitAreas = document.getElementsByClassName('hitArea');
    alert(hitAreas.length);
    for(hitArea in hitAreas)
    {
        alert(hitAreas[hitArea]);
        hitAreas[hitArea].className = 'hitArea_practice';
    }

The alert(hitAreas.length); line is properly returning the number of elements (7, from the html below) with the classname 'hitArea', but when I iterate through hitAreas, it's only changing the classnames for every other element on the page. Halfway through it returns undefined as a value for alert(hitAreas[hitArea]); assumably because it's trying to reference array elements beyond an index of 6.

Body of the html page:

        <body onload="toggleHotspotHints();">
<div>
    <img src="Dashboard1.jpg" width="1440" height="795" />
    <div class="hitArea" style="top: 55px; left: 230px; width: 72px; height: 17px;" onclick="gotoPage('BatchReconcile/1-ClaimsReconcileMenu');"></div>
    <div class="hitArea" style="top: 55px; left: 319px; width: 72px; height: 17px;" onclick="gotoPage('Eligibility/PP Elig 1');"></div>
    <div class="hitArea" style="top: 55px; left: 409px; width: 72px; height: 17px;" onclick="gotoPage('REPORTS/5-Dashboard Reports List');"></div>
    <div class="hitArea" style="top: 137px; left: 260px; width: 145px; height: 21px;" onclick="gotoPage('Dash2_Messages');"></div>
    <div class="hitArea" style="top: 223px; left: 247px; width: 126px; height: 19px;" onclick="gotoPage('ClaimsList_Failed');"></div>
    <div class="hitArea" style="top: 242px; left: 247px; width: 126px; height: 14px;" onclick="gotoPage('PayerReportList');"></div>
    <div class="hitArea" style="top: 258px; left: 247px; width: 126px; height: 14px;" onclick="gotoPage('ADM/1_trending graph');"></div>
</div>

Live demo: http://jsfiddle.net/simevidas/LE6UN/


回答1:


Šime Vidas pointed out that getElementsByClassName retuns a live nodeList, meaning the collection stored will be updated as things are changed (here the class attribute).

var hitAreas = document.getElementsByClassName('hitArea'),
    hitAreasLength = hitAreas.length;

while ( hitAreasLength-- > 0) {
    hitAreas[hitAreasLength].className = 'hitArea_practice';
}

I'm not sure if this is the nicest code, but it works :)

jsFiddle.



来源:https://stackoverflow.com/questions/5187918/javascript-for-in-seems-to-only-return-every-other-index-in-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!