简体   繁体   中英

jQuery nth-child only selecting first element

I am trying to add a on click function on the specific child of .article which will show certain wikipedia link base on the pageid received from the request. But all the .article are pointing to the same page.

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);
}

Answer is quite simple. You ran into javascript scope problem. Have a look at the immediate function call. Read more here. 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)
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM