点击链接以进行API调用

时间:2019-03-05 15:04:51

标签: javascript jquery

我做了一个可以进行API调用并在页面上显示内容的函数?首次加载时有效。

我想要的是每次我单击链接时都以不同的结果拨打电话。 这将再次请求API并在页面上显示其他内容

JS代码:

   var cat = "health";

function apiCall(cat){
  $(".cat").on("click",function(e) {
  e.preventDefault(); // cancel the click 
  $.getJSON("https://newsapi.org/v2/top-headlines?country=us&category=" +
    $(this).attr("data-cat") +  
    "&apiKey=xxx", function(a) {
    for (i = 0; i < a.articles.length; i++) {
      var titulo = a.articles[i].title;
      var descricao = a.articles[i].description;
      var autor = a.articles[i].author;
      var link = a.articles[i].url;
      var linkDaImagem = a.articles[i].urlToImage;
      var dataPublicacao = a.articles[i].publishedAt;

      $(".card").append(
        '<div class="item"><h2>' + titulo + "</h2>" +
          //caracter of scape: "quotes" and '+'
          '<img src="' + linkDaImagem + '">' +
          '<p class="publishedAt">' + dataPublicacao + "</p>" +
          "<p>" + descricao + "</p>" +
          "<p>" + autor + "</p>" +
          //caracter of scape: "quotes" and '+'
          '<a href="' + link + '">Read more</a>' + 
        "</div>"
      )//closes .append
    }//closes for
 })//closes getJSON and function(a)
 })//closes click and function(e)
 }//closes apiCall()
apiCall(cat);

HTML摘录:

 <li><a class="cat" href="#" data-cat="business">Business</a></li>
    <li><a class="cat" href="#" data-cat="entertainment">Entertainment</a></li>
    <li><a class="cat" href="#" data-cat="general">General</a></li>
    <li><a class="cat" href="#" data-cat="health">Health</a></li>

但这不会转到请求的类别(var cat)。 完成正确呼叫的步骤应该是什么?

1 个答案:

答案 0 :(得分:0)

1。。使用类和数据属性:

<li><a href="#" class="cat" data-cat="business">Business</a></li>
<li><a href="#" class="cat" data-cat="technology">Tech</a></li>

2。。分配事件处理程序

$(".cat").on("click",function(e) {
  e.preventDefault(); // cancel the click 
  $.getJSON("https://newsapi.org/v2/top-headlines?country=us&category=" +
    $(this).attr("data-cat") +  
    "&apiKey=xxx", process);
});

$("[data-cat=general]").click(); // load the first one   

3。简化过程

function process(a) {
  $.each(a, function(article) {
    $(".card").append(`
        <div class="item"><h2>${article.title}</h2>
          <img src="${article.urlToImage}">
          <p class="publishedAt">${article.publishedAt}</p>
          <p>${article.description}</p>
          <p>${article.author}</p>
          <a href="${article.url}">Read more</a>
        </div>`) //closes .append
  }) //closes each
}