2015-09-27 38 views
2

我试图让用户输入一个搜索词,然后使用该词作为标签来搜索Flickr的API。我设法让基本的搜索工作,但在这之间出现了问题,并添加了按钮点击事件。有人能帮我解决吗?我觉得这是我看不到的东西,我对很新。捕获用户输入并用作搜索Flickr API,需要按钮点击工作

<!DOCTYPE html> 
<html> 

<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" /> 
    <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> 
    <script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script> 
    <script> 
    $("button").click(function() { 
     var searchTerm = $("input:text").val(); 
     var flickrApi = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?"; 
     $.getJSON(flickrApi, { 
      tags: "searchTerm", 
      tagmode: "any", 
      format: "json" 
     }) 
     .done(function(data) { 
      $.each(data.items, function(i, item) { 
      $("<img>").attr("src", item.media.m).appendTo("#images"); 
      if (i === 3) { 
       return false; 
      } 
      }); 
     }); 
    }) 
    </script> 
</head> 

<body> 
    <input type="text" id="search"> 
    <button type="submit">Search</button> 
    <div id="images"></div> 
</body> 

</html> 
+0

HM,它为我工作。你能指出什么地方出了问题吗?编辑:你应该明确地添加:$(document).ready(function(){...你的代码在这里...}); – jacksbox

回答

0

尝试在你的变量 “搜索关键词” 删除双引号改变:

$.getJSON(flickrApi, { 
    tags: "searchTerm", 
    tagmode: "any", 
    format: "json" 
}) 

$.getJSON(flickrApi, { 
    tags: searchTerm, // Local variable. 
    tagmode: "any", 
    format: "json" 
}) 

顺便说一句,你需要放置一个jQuery函数内部代码。当DOM准备好通过jQuery/Javascript代码与HTML标记进行交互时,jQuery功能将成功运行。

$(document).ready(function() 
{ 
    // jQuery/Javascript code goes here... 
}); 

或为$(document).ready()速记:

$(function() 
{ 
    // jQuery/Javascript code goes here... 
}); 

Demo

+0

非常感谢您的帮助!我还没有机会尝试它,因为我不得不跳过其他工作,但我会尽快尝试。 –