我试图让用户输入搜索词,然后使用该词作为标签来搜索 Flickr 的 API。我设法让基本搜索正常工作,但在添加按钮点击事件之间出现了问题。有人可以纠正我吗?我觉得这是我没有看到的小东西,我对 jquery 很陌生。和 json .
<!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>
最佳答案
尝试删除变量“searchTerm”中的双引号更改:
$.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...
});
关于javascript - 捕获用户输入并用作 Flickr API 的搜索,需要让按钮点击正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32809999/