2014-02-13 14 views
1

更改圖像源動態圖像的源圖像。當我的頁面加載我從數據庫生成的幾個小圖片:上點擊

$.getJSON('inc/API.php', 
{ 
    command: "get_ads_to_display" 
}, 
function(result){ 
    $("#img_main").attr('src', 'images/'+result[0].ad_image_filename); 
    for(var i = 0; i<result.length; i++) 
    { 
     $("<div class='div_item_container'>"+ 
      "<div class='div_ad_name'>"+result[i].ad_publisher+"</div>"+ 
      "<div class='div_ad_image'><img src='images/"+result[i].ad_image_filename+"' /></div>"+ 
     "</div>").appendTo("#gallery"); 
    } 
}); 

我也有在主圖像img_main。我想要的是將此主圖像的src更改爲單擊小圖像的來源(它應該是某種圖庫)。我試過這個getJSON函數後:

$(".div_ad_image img").click(function(){ 
    $("#img_main").attr('src', $(this).attr('src')); 
}); 

但它沒有工作,圖像src沒有改變。嘗試使用不同的選擇器,嘗試將此代碼放在appendTo("#gallery");部分後面,但仍然沒有結果。那麼怎麼做呢?

回答

1

您需要使用event delegation因此該點擊事件可以被綁定到你的動態創建的圖像:

$('.div_item_container').on('click', '#div_ad_image img', function() { 
    $("#img_main").attr('src', $(this).attr('src')); 
}); 
+0

是的,它的工作!非常感謝你!我也嘗試了'on'事件委託,但沒有正確編寫代碼,因此無法正常工作。現在所有東西都像魅力一樣,只需將'#div_ad_image'改爲'.div_ad_image' - 對不起,我的糟糕之處,在我試圖對代碼進行所有更改後,對選擇器感到困惑。非常感謝你!!一旦系統允許我在5分鐘內完成,將接受您的答案。 – Igal

1

當你在動態添加圖像。

您需要使用Event Delegation。您必須使用委託事件方法使用.on()

$('#gallery').on('click', '.div_ad_image img', function() { 
    $("#img_main").attr('src', $(this).attr('src')); 
}); 

委託事件有優勢,他們可以處理來自被添加到該文件在稍後的時間後代元素的事件。

+0

非常感謝您的意見!欣賞它! – Igal