使用AJAX和innerHTML遇到麻烦

时间:2018-10-28 14:03:25

标签: javascript ajax

我正在尝试学习AJAX,所以我使用https://jsonplaceholder.typicode.com创建了一个程序来获取数据并显示它,我还添加了一个按钮,用于显示每个帖子的注释,并且该代码适用于前几个帖子,对于以后的帖子(从30开始),我会遇到以下错误:

  

未捕获的TypeError:无法设置未定义的属性“ innerHTML”

现在有时候,我不知道如何,但是代码可以在以后的文章中使用,但是有时候却不行,这很令人困惑,我使用console.log查看是否检索到了注释,然后总是会在单击按钮时登录到控制台,对于某些按钮,它只是没有插入DOM中。感谢您的帮助,谢谢!

HTML代码:

<div class="main">
    <h2 class="heading"></h2>

</div>
<button onclick="getPost(0,10)">1</button>
<button onclick="getPost(11,20)">2</button>
<button onclick="getPost(21,30)">3</button>
<button onclick="getPost(31,40)">4</button>
<button onclick="getPost(51,60)">5</button>
<button onclick="getPost(61,70)">6</button>
<button onclick="getPost(71,80)">7</button>
<button onclick="getPost(81,90)">8</button>
<button onclick="getPost(91,99)">9</button>

还有JS:

let main = document.querySelector('.main');
let postData = document.querySelector('.post-main');
let pagination = document.querySelector('.paginationDiv')
let commentSection;
let str = "";
let start = 0;
let end = 10;
let commentsAr = [];
let dat = "";
// Get posts

function getPost(start, end) {

    $.get('https://jsonplaceholder.typicode.com/posts', function (data, status) {
        let lth = data.length;
        for (let i = start; i <= end; i++) {

            str += `<div class="jpg"><h2 class="heading">${i} . ${data[i].title}</h2>
        <p class="post-main">${data[i].body}</p></div><span class="comments"></span><button id="${i}" class="showComments">Get comments</button> <br>`;

            console.log(`Post retrieval status: ${status}`);
        }


        main.innerHTML = str;

        let h = document.querySelectorAll('.showComments');
        commentSection = document.querySelectorAll('.comments');
        for (const g of h) {
            g.addEventListener('click', function () {
                if (g.id === 0) {
                    getComments(g.id++);
                } else {
                    getComments(g.id);
                }
            })
        }


    })
}


function getComments(val) {

    $.get(`https://jsonplaceholder.typicode.com/comments?postId=${val}`, function (data, status) {
        // console.log(data[val].email);


        for (let x = 0; x <= data.length - 1; x++) {
            commentsAr.push(data[x]);
        }

        dat += `<ol>`
        for (let v = 0; v <= commentsAr.length - 1; v++) {
            console.log(commentsAr[v]);

            dat += `
        <li>${commentsAr[v].name} <br> <i>${commentsAr[v].email}</i> <p><b>${commentsAr[v].body}</b></p></li> <br>`;
        }
        dat += `</ol>`

        commentSection[val].innerHTML = dat;
        dat = "";
        commentsAr.length = 0;
    })
}



getPost(start, end);

Codepen链接:https://codepen.io/goprime/pen/YJgLPM

0 个答案:

没有答案