Dad*_*daB 0 javascript for-loop
我有以下代码使用谷歌图片搜索API:
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('contentimg');
contentDiv.innerHTML = '';
// Loop through our results, printing them to the page.
var results = searcher.results;
for (var i = 1; i < results.length; i++) {
// For each result write it's title and image to the screen
var result = results[i];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
Run Code Online (Sandbox Code Playgroud)
问题是,它给了我3个图像结果.如何打破一个循环并只显示第一个而不是3个图像?如果我改变for (var i = 1; i < results.length; i++)到for (var i = 3; i < results.length; i++)它只显示一个图像,但图像显示的是一个第三,我需要证明一日一个:)请咨询
根本不要使用for循环.只需i用0 替换所有实例.
google.load('search', '1');
function searchComplete(searcher) {
// Check that we got results
if (searcher.results && searcher.results.length > 0) {
// Grab our content div, clear it.
var contentDiv = document.getElementById('contentimg');
contentDiv.innerHTML = '';
var result = searcher.results[0];
var imgContainer = document.createElement('div');
var newImg = document.createElement('img');
// There is also a result.url property which has the escaped version
newImg.src = result.tbUrl;
imgContainer.appendChild(newImg);
// Put our title + image in the content
contentDiv.appendChild(imgContainer);
Run Code Online (Sandbox Code Playgroud)
0表示返回的第一个项目(编程中的几乎所有数字序列都从0开始!)所以其他所有结果都将被忽略.