我尝试根据图片构建字符串是否存在,如果存在,则构建图像标记,如果它没有创建带有类的空div标签。 image我怎样才能实现这个目标 - 有些人可以给我一些帮助
$('#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 :(得分: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
});