gpt4 book ai didi

javascript - 打破 JavaScript 循环

转载 作者:行者123 更新时间:2023-11-28 13:48:52 25 4
gpt4 key购买 nike

我有以下代码来使用 Google 图片搜索 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);

问题是,它给了我 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);

0 表示返回的第一项(编程中几乎所有数字序列都从 0 开始!),因此所有其他结果将被忽略。

关于javascript - 打破 JavaScript 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12198077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com