jQuery nth-child只选择第一个元素

时间:2017-12-31 14:41:29

标签: javascript jquery

我正在尝试为.article的特定孩子添加点击功能,该功能会根据从请求中收到的wikipedia显示某个pageid链接。但是所有.article都指向同一页面。

HTML:

<section id="body-article">
    <div id="body-container">

    </div>
</section>

的JavaScript(jQuery的):

function SendRequest(searchEntry){
    $.ajax({
        url: `https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch=${searchEntry}`,
        type: 'GET',
        dataType: 'jsonp',
        headers: {'Api-User-Agent': 'WikiReader/0.1.0'}
      }).done(function(data, status) {
          console.log(data);
          GenerateArticle(data);
      }).fail(function(data, status) {
        console.log("ERROR! " + status);
      });
}

function GenerateArticle(data){
    //shows all the article in a div
    var totalArticleLength = data.query.search.length;
    for(var i=0;i<totalArticleLength;i++){
        var title= data.query.search[i].title;
        var pageid=data.query.search[i].pageid;
        var snippet=data.query.search[i].snippet;
        //responsible for showing single data
        CreateSingleArticle(title,pageid,snippet);
        // PROBLEM IS WITH THE BELOW LINE
        $(`.article:nth-child(${i+1})`).on("click",function(){
            window.open(`https://en.wikipedia.org/?curid=${pageid}`, 'Wikipedia', 'window settings');
        })
    }

}
function CreateSingleArticle(title,pageid,snippet){
    //creates a individual data
    html =
    `<div class="article">
        <div class="side-bar"></div>
        <div class="article-container">
            <div class="article-header">
                ${title}
            </div>
            <div class="snippet">
                ${snippet}
            </div>
        </div>
    </div>`
    $("#body-container").append(html);
}

1 个答案:

答案 0 :(得分:-1)

答案很简单。你遇到了javascript范围问题。看一下即时函数调用。在这里阅读更多。 http://tobyho.com/2011/11/02/callbacks-in-loops/

for(var i=0;i<totalArticleLength;i++){
(function(index, pageId){

        var title= data.query.search[index].title;
        var pageid=data.query.search[index].pageid;
        var snippet=data.query.search[index].snippet;
        //responsible for showing single data
        CreateSingleArticle(title,pageid,snippet);
        // PROBLEM IS WITH THE BELOW LINE
        $(`.article:nth-child(${index+1})`).on("click",function(){
            window.open(`https://en.wikipedia.org/?curid=${pageId}`, 'Wikipedia', 'window settings');
        })
})(i, data.query.search[i].pageid)
    }