1

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);
}
Mamun
  • 66,969
  • 9
  • 47
  • 59

1 Answers1

-1

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)
    }
Fachher
  • 28
  • 4
  • 1
    @SadikshyaLuintel: This is a solution for former days of JS. Since you're using template literals, you might as well use other newer features, like `let i = 0;` instead of `var i = 0;` with the closure. –  Dec 31 '17 at 15:04
  • To all downvoters. Please leave a message why you have down voted this post. This helps me to improve my self. – Fachher Dec 31 '17 at 15:07
  • @SadikshyaLuintel rock star answer is the newer solution which you should prefer. Haven't recognized that you are using newer ecmascript. – Fachher Dec 31 '17 at 15:09
  • With the scoping, I don't think the `nth-child` specific part is needed anymore, since `pageId` will be scoped with the appropriate iterated row. Just make it react on `.article` click. – Jared Farrish Dec 31 '17 at 15:11