当值为空时,我无法返回我想要的图像[关闭]

Posted

技术标签:

【中文标题】当值为空时,我无法返回我想要的图像[关闭]【英文标题】:I Cant return image I want when value is null [closed] 【发布时间】:2020-06-30 19:00:57 【问题描述】:

如果我从我的 api 中提取的图像为空,我会尝试返回默认图像, 但是我放的任何东西都不会返回我的默认/占位符图像,我尝试了 null、void、false 等,没有任何效果,当我输入 value = "" 时,即使它不为 null,它也会显示我的默认图像,

json 看起来像

我试图从 app3.js 开始工作的区域/////////////////////////////// //////////////////////////////////////////////p>

 var $img2 = $("<img />").attr('src', data2.events["1"].performers["0"].image );

    var userImage = $("<img />").attr("src","https://imagemagick.org/image/gradients/linear_gradient.png");

         var $imgnew = ($img2, (key, value) => 
  if (value ===  null) 
    return userImage;

  
  return value;

)  

$('#img2').append($imgnew);

完整的json ///////////////////

meta: …, in_hand: …, events: Array(10)
meta: geolocation: null, per_page: 10, total: 14, took: 4, page: 1
in_hand: 
events: Array(10)
0: links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5055747, …
1:
links: []
event_promotion: null
conditional: false
is_open: false
id: 5161557
stats: visible_listing_count: null, dq_bucket_counts: null, average_price: null, lowest_sg_base_price_good_deals: null, lowest_price_good_deals: null, …
title: "Amarillo Venom at Salina Liberty"
announce_date: "2019-12-21T00:00:00"
score: 0.361
access_method: null
announcements: 
taxonomies: (2) […, …]
type: "football"
status: "normal"
description: ""
datetime_local: "2020-03-21T13:00:00"
visible_until_utc: "2020-03-21T22:00:00"
time_tbd: false
date_tbd: false
performers: Array(2)
0: image: null, primary: true, colors: null, images: …, has_upcoming_events: true, …
1: image: null, colors: null, images: …, has_upcoming_events: true, id: 114910, …
length: 2
__proto__: Array(0)
url: "https://seatgeek.com/amarillo-venom-at-salina-liberty-tickets/football/2020-03-21-1-pm/5161557"
created_at: "2019-12-21T16:00:49"
popularity: 0.46
venue: links: Array(0), metro_code: 678, postal_code: "67401", timezone: "America/Chicago", has_upcoming_events: true, …
enddatetime_utc: null
short_title: "Amarillo Venom at Salina Liberty"
datetime_utc: "2020-03-21T18:00:00"
datetime_tbd: false
__proto__: Object
2: links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5161560, …
3: links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251570, …
4: links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251569, …
5: links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251400, …
6: links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251566, …
7: links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251567, …
8: links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251568, …
9: links: Array(0), event_promotion: null, conditional: false, is_open: false, id: 5251565, …
length: 10
__proto__: Array(0)
__proto__: Object

完整的app3.js //////////////////////////////////// /////////////////////////

function myFunction() 
  var x = document.getElementById("myText").value;
  document.getElementById("demo4");



            var list = 'boston';
            var list2 = 'celtics';

                            $.getJSON("https://api.seatgeek.com/2/events?q="+x+"&client_id=MjA1NTgxMTN8MTU4MDY3MjIzNy43OQ", function(data2) 


        //        events["0"].performers["0"].image


                  var $img = $("<img />").attr('src', data2.events["0"].performers["0"].image);

                  var $img2 = $("<img />").attr('src', data2.events["1"].performers["0"].image );

       //         var $img = $("<img />").attr('src', data2.events.performers[0].images.huge); 

                           //     events[1].performers[""0""].image

                var list3 = data2.events;

                var event2 = list3.title;                



                var list5 = data2.events["0"].title;    

                 var price1 = data2.events["0"].stats.average_price;                


//                var list5new = list5 + " " + price1;                


                var list6 = data2.events["1"].title;                 

                var price2 = data2.events["1"].stats.average_price;                  

//                var list6new = list6 + " " + price2;



                var list7 = data2.events["2"].title;

                 var price3 = data2.events["0"].title;                 




                 var buy = data2.events["0"].url;


                 var buy3 = data2.events["1"].url;    

       //         console.log(href);


//                 var str = "Free Web Building Tutorials!";
   var buy2 = buy.link(data2.events["0"].url);                

   var buy4 = buy3.link(data2.events["0"].url);                              




                var hi = 'NA'     

    var newlink = (JSON.stringify(list5, (key, value) => 
  if (value === undefined) 
    return hi;

  
  return value;
 
))     


//    if (list5.value === "undefined")
//    console.log('the property is not available...'); // print into console
//


//                                
//  if (typeof list5 === "undefined") 
//    txt = "x is undefined";
//      
//    console.log('nada')  
//   else 
//    txt = "x is defined";
//                                  
//                                
          // var userImage = "https://imagemagick.org/image/gradients/linear_gradient.png"; 

                         //      var userImage2 = "https://imagemagick.org/image/gradients/linear_gradient.png"; //
    var userImage = $("<img />").attr("src","https://imagemagick.org/image/gradients/linear_gradient.png");

         var $imgnew = ($img2, (key, value) => 
  if (value.getAttribute('src') == "") 
    return userImage;

  
  return value;
 
)                    


                var hi = 'NA'

    var link1 = (JSON.stringify(price1, (key, value) => 
  if (value === null) 
    return hi;

  
  return value;
 
))

                    var hi = 'NA'

    var link2 = (JSON.stringify(price2, (key, value) => 
  if (value === null) 
    return hi;
  
  return value;
 
))
      //          console.log(list3)

          //      console.log(list5new)  
                console.log(data2)  


                 $("#demo4").append(list5 + " - " + "Price" + " " + link1 );
                 $("#link").append( buy2);                
                 $("#demo5").append(list6 + " - " + "Price" + " " + link2);                
                 $("#link2").append(buy4);
                 $('#img1').append($img);
                 $('#img2').append($img2);    
             //        $('#img3').append(userImage);                                  

                 $(document).ready(function()

//                                                 $("p").click(function()
//    alert("The paragraph was clicked.");    
//
//                                                 );
            if( $("#demo4").css('display') == 'none')  
            $("#error").show();
        

                );

                $(document).ready(function()

            if( $("#demo4").css('display')) 
            $("#error").hide();
        


            $("button").click(function()
            $("#error").hide();
  );
                );

);
//            $.getJSON("https://api.seatgeek.com/2/events?q=boston+celtics&client_id=MjA1NTgxMTN8MTU4MDY3MjIzNy43OQ", function(data2) 
//    //data is the JSON string 
//                console.log(data2);
//);


html /////////////////////////////////////// ////////

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Event finder</title>
  <link rel="stylesheet" href="style2.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>     

</head>
<body>






 <div id="top"> 
    <h2>FindYourTickets</h2>

    <br>

    <h2 class="hi">Get Started here</h2>
    <br>
    </div>
   <br>
    <div class="center">

<!--        <h2>City</h2>-->
            <input id="myInput2" type="text" placeholder="City(Optional)">

    <br>    
<!--        <h2>Search</h2>-->

    <br>




  <input type="text" id="myText" placeholder="Search" value="">

<p></p>

<button class="button" onclick="myFunction()"><h2>Search</h2></button>    




    <br>
    <br>

    <button class="button"><a href="index3.html"><h2>Clear</h2></a></button>






    </div>
<br><br>
<!--
<div id="myDIV">
  <p>I am a paragraph.</p>
  <div>I am a div element inside div.</div>
  <button>I am a button</button>
  <button>Another button</button>
  <p>Another paragraph.</p>
</div>
-->


    <!-- <div class="main">
    <div class="header">
      <h1>OpenWeatherMap API</h1>
      <p>Enter any city name in the input box below to get the data</p>
    </div> -->

<!--
   <button type="button" onclick="alert('Hello world!')">Click Me!</button>
<h1 class="name2" id="name2">hi</h1>  
-->

<script src="app3.js"></script>

<!--
<h1>This is a Heading</h1>
<p>This is a paragraph.</p>  
-->

<!--     <div id="img3"></div>-->
    <div id="wrapper">
    <div id="error"> <h4>No results</h4></div>
 <div id="demo4"></div>   
   <div id="link"></div>

        <div id="img1"></div>

        <br>
        <br>
           <br>
        <br>

        <div id="demo5"></div>  
  <div id="link2"></div>

        <div id="img2"></div>



    <span class = "my_class"></span>




          <ul id="result2"> </ul> 



    </div>



</body>
</html>

【问题讨论】:

【参考方案1】:

您的代码比它需要的更复杂。您只需要确定 image 属性是否为空/null,然后提供默认值(如果是)。因此,您可以使用 || 将空值合并到您的默认路径。试试这个:

var imgSrc = data2.events[1].performers[0].image || "https://imagemagick.org/image/gradients/linear_gradient.png";
$("<img />").prop('src', imgSrc).appendTo('#container');

请注意,新的img 元素被附加到另一个元素。您的原件试图在 img 中附加 img,这是不可能的。

【讨论】:

以上是关于当值为空时,我无法返回我想要的图像[关闭]的主要内容,如果未能解决你的问题,请参考以下文章

当值为空时,Django modelSerializer form.is_valid() 为真

spring boot加mybatis使用Map返回时,当值为空时属性也会没有(转)

当值为空时获取计数

当值为空时文本框“锁定”(需要整数)

FluentValidation - 仅当值不为空时检查值是表达式

Spring - 仅当值不为空时才设置属性