我的HTML中有一个类的li元素列表。我想把它们全部抓起来并放在一个阵列中,然后找出我抓了多少。但是,每当我尝试输出.length所在的数组的document.getElementsByClassName属性时,它只会导致0。这是我的代码:

function activateFeedMain() {
        console.log('Function Called');
        var clickInfo = document.getElementsByClassName('miniInfo');
        var showInfo = document.getElementsByClassName('moreInfo');

        console.log(clickInfo.length);
    }

    activateFeedMain();


这是HTML:
    
    

<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta id="refresh" http-equiv="refresh" content="300">
<title>News and Events</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="scripts/hfreplacement.js"></script>
<script type="text/javascript" src="scripts/news.js"></script>
<style type="text/css">
    #content-col1 ul {list-style-type: none;}
    #content-col1 ul li {background-color: #66FFCC; border-radius: 5px; padding: 12px; margin-bottom: 8px;}
    #content-col1 ul li:hover {background-color: #FFFFCC;}
    .description {font-weight: bold; font-style: italic;}
    .date, .type, .approval {font-size: 12pt; padding-right: 25px; padding-left: 18px; display: inline-block; border-right: 1px solid black;}
    .date {padding-left: 0px;}
    .approval {border: none;}
    .invisible {display: none;}
    #content-col1 ul a:hover {text-decoration: none;}
    #content-col1 ul a {text-decoration: none; cursor: pointer;}

</style>
</head>

<body>
<div id="head"></div>

<div id="content">
    <div id="content-col1">
        <p class="note">Refresh for updates</p>
        <script>newsContent();</script>
    </div>

    <div id="content-col2">
        <h1>Latest</h1>
        <ul>
        </ul>
    </div>
</div>

<div id="foot"></div>
<script type="text/javascript">
    function activateFeedMain() {
        console.log('Function Called');
        var clickInfo = document.getElementsByClassName('miniInfo');
        var showInfo = document.getElementsByClassName('moreInfo');

        console.log(clickInfo.length);
    }

    activateFeedMain();
</script>
</body>
</html>


脚本newsContent();将所有li安装在ul中。附带说明一下,当我使用console.log(clickInfo)时,它为我提供了数组列表。与.length属性有关...

另外,当我尝试使用console.log(clickInfo[1]);时,它给了我未定义的...

最佳答案

Working fiddle

您遇到此问题的原因是,您的newsContent函数正在动态地创建与activateFeedMain函数并行的异步在页面上创建内容的过程。由于同时调用它们,因此newsContent函数中的元素尚未在调用activateFeedMain时创建。

您可以通过为newsContent提供一个回调函数来解决此问题,该函数将在完成运行后执行。

function activateFeedMain() {
    console.log('Function Called');
    var clickInfo = document.getElementsByClassName('miniInfo');
    var showInfo = document.getElementsByClassName('moreInfo');

    console.log(clickInfo.length);
}

// Call activateFeedMain() once newsContent has finished
newsContent(activateFeedMain);


在定义newsContent的地方,将其设计为采用如下所示的回调:

function newsContent(callback){

    ...

    // When this function is done
    if(typeof callback === 'function'){
        callback();
    }
}

10-06 02:41