2015-11-17 25 views
1

我想使用ajax調用從目錄加載所有圖像,並在加入html後接受它。我已成功加載所有圖像。但我的問題是,我不能在jQuery插入html後訪問它的屬性。在ajax加載數據後獲取jQuery數據

如何在通過jQuery ajax調用添加圖像屬性後訪問圖像屬性。

訪問圖片src我jQuery代碼是

 $("button").click(function(){ 
     $("#div1").load("demo.php"); 
    }); 
     $("#div1 img").click(function(){ 
     console.log($(this).attr("src")); 
     });   

我的HTML是:

 <div id="div1"></div> 
     <button>Click Here</button> 

和我demo.php是

 <?php 
     $directory = /path/to/folder/; 
     $images = glob($directory . "*.jpg"); 
     foreach($images as $image) 
     { 
    echo "<img class='imgr' src='$image'/>"; 
    } 
     ?> 

我能加載圖像到div1元素,但我無法訪問其屬性。我已將'#div1 img'更改爲'img'和'.imgr',但沒有運氣。

+0

試試這個:'$( '#DIV1')上( '點擊', 'IMG',函數(){ 的console.log($(本)。 ATTR( 「SRC」)); });' – Rayon

回答

1

這是因爲數據是動態加載的。

變化;

$("#div1 img").click(function(){ 
    console.log($(this).attr("src")); 
}); 

$("#div1").on("click", "img", function() { 
    console.log($(this).attr("src")); 
}); 
1

您不能綁定點擊加載腳本時不存在元素的事件。 你可以改變這一點:

$("#div1 img").click(function(){ 
    console.log($(this).attr("src")); 
}); 

這樣:

$('#div1').on('click', "img", function(){ 
    console.log($(this).attr("src")); 
}); 
1

你需要有家長的div單擊事件,以委託點擊事件不屬於DOM的一部分,但孩子們,請事件代表團檢查了這link

試試這個:

$("#div1").on('click', 'img', function(){ 
    console.log($(this).attr("src")); 
    }); 
+0

'img'應該用''引號括起來! – Rayon

+0

並在'.on'後刪除點 – Iecya

1

我會建議使用$(document).on("click" , "" , function() {});

$(document).on("click", "#div1 img", function() { 
    console.log($(this).attr("src")); 
});