2017-01-21 82 views
0

我想建立一個字符串取決於圖像是否存在與否,如果它存在然後建立一個圖像標籤,如果它不創建一個空的div標籤與一類。沒有像我怎樣才能做到這一點 - 可能有些給我一些幫助檢查圖像是否存在與建立字符串

$('#search_movies').select2({ 
    ajax: { 
     url: "http://localhost:8000/admin/tmdb/search", 
     dataType: 'json', 
     delay: 250, 
     type: 'POST', 
     results: function (data, page) { 
      console.log(data); 
      return { results: data.d }; 
     }, 
     data: function (params) { 
      return { 
      q: params.term, // search term 
      // page: params.page 
      }; 
     }, 
     processResults: function (data, params) { 
      // parse the results into the format expected by Select2 
      // since we are using custom formatting functions we do not need to 
      // alter the remote JSON data, except to indicate that infinite 
      // scrolling can be used 
      //params.page = params.page || 1; 

      console.log(data) 
      return { 
      results: data.items, 
      // pagination: { 
      // more: (params.page * 30) < data.total_count 
      // } 
      }; 
     }, 
     cache: false 
     }, 
     escapeMarkup: function (markup) { return markup; }, // let our custom formatter work 
     minimumInputLength: 1, 
     templateResult: formatRepo, // omitted for brevity, see the source of this page 
     templateSelection: formatRepoSelection // omitted for brevity, see the source of this page 
    }); 


function formatRepo(repo) { 
    if (repo.loading) return repo.text; 


    var markup = '<div data-id="' + repo.id + '" class="option clearfix">'; 
     markup += '<div class="option-image"><img alt="" src="' + repo.image + '"></div>'; 
     markup += '<div class="option-content">'; 
      markup += '<h4>' + repo.title + '</h4>'; 
      markup += '<h4>' + repo.release_date + '</h4>'; 
      markup += '<h4>' + repo.popularity + '</h4>'; 
     markup += '</div>'; 
    markup += '</div>'; 


    return markup; 
} 


function formatRepoSelection (repo) { 
    return repo.title || repo.text; 
} 
+0

您是否試圖確定'url'是否指向圖像文件的有效路徑? – guest271314

+0

是的這是正確的代碼檢查,但不建立字符串 – ONYX

+0

什麼代碼設置repo.loading爲true?並設置repo.text –

回答

0

反而使formatRepo回報的標記,使標記傳遞給像一個回調函數。

function formatRepo(repo, markupCallback) { 
    function imageExists(url, callback) { 
     var img = new Image(); 
     img.onload = function() { callback(true); }; 
     img.onerror = function() { callback(false); }; 
     img.src = url; 
    } 

    imageExists(repo.image, function(exists) { 
     var markup = ''; 
     if(exists) { 
      markup += '<img src="' + repo.image + '">'; 
     } else { 
      markup += '<div class="no-image"></div>'; 
     } 
     // pass markup to markupCallback 
     markupCallback(markup); 
    }); 
} 

// and then use it like 
formatRepo(myRepo, function(markup){ 
    // use markup here 
}); 
+0

@ONYX似乎不可能,因爲它都傳遞給'select2',我認爲它是一個庫函數,你不能修改它適應'formatRepo'的異步特性。 –