[英]How can I populate html elements into another page?
這是我在script.js中的jQuery函數。此函數用於從Flicker獲取feed並填充結構。
我想將html結構填充到另一個名為“items.html”的html頁面中
$function getImages(){
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=90528678@N03&lang=en-us&format=json&jsoncallback=?", displayImages);
function displayImages(data) {
// Start putting together the HTML string
var htmlString = '';
// Now start cycling through our array of Flickr photo details
$.each(data.items, function(i,item){
// Here's where we piece together the HTML
htmlString += '<div class="item_wrapper" name="'+item.title+'">';
htmlString += '<img class="item_picture" src="' + item.media.m + '" alt=""/>';
htmlString += '<div class="item_data">';
htmlString += '<div class="item_company">';
htmlString += '<h3 class="fi se en">'+item.title+'</h3>';
htmlString += '</div>';
htmlString += '<div class="item_title">';
htmlString += '<h3 class="fi">'+item.title+'</h3>';
htmlString += '<h3 class="se">'+item.title+'</h3>';
htmlString += '<h3 class="en">'+item.title+'</h3>';
htmlString += '</div>';
htmlString += '</div>';
htmlString += '</div>';
});
// Pop our HTML in the DIV tag of items.html
// Here's the problem.
$('div').html(htmlString);
}
}
那我該怎么辦呢? 謝謝 !!!
您可以使用ajax加載函數來加載網頁中的html內容。
$('div').load("file.html");
您可以使用以下命令將另一個html頁面加載到元素中:
$('div').load("items.html");
您也不應該使用字符串連接來構建dom元素。
使用這樣的東西:
var div = $('<div/>');
$.each(data.items, function(i, image) {
var item = $('<div/>').addClass("item_wrapper").attr('name', image.title);
$('<img/>').attr('src', image.media.m).appendTo(item);
item.appendTo(div);
});
$('div').html(div);
等等...
這是一個有效的簡化版本。
getImages();
function getImages(){
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=90528678@N03&lang=en-us&format=json&jsoncallback=?",
function(data) {
var htmlString = '';
$.each(data.items, function(key, value){
htmlString += '<div>'+value.title+'</div>';
htmlString += '<img src="'+value.media.m+'">';
});
$('div').html(htmlString);
});
}
我實際上不知道為什么你的版本不起作用。
有可能getJSON的回調需要是匿名無名稱函數,這就是displayImages函數無法正常工作的原因。 我無法讓它發揮作用。
你的函數聲明前面有一個$。 也許這導致了這個問題。
雖然html字符串插入工作,但像Josh說,DOM插入節點比html插入更好。 如果你只是在尋找一個快速而骯臟的解決方案html字符串插入可能沒問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.