在ajax加载数据后获取有关jquery的数据

在ajax加载数据后获取有关jquery的数据

问题描述:

I wanted to load all images from a directory using ajax call and accept one after it is added to html. I have successfully load all images. But My problem is that i can't access its attribute in jQuery after it is inserted in html.

How can I access an image attribute after it is been added by jQuery ajax call.

My jQuery code for accessing image src is

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

my html is :

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

and my demo.php is

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

I am able to load images to the div1 element but I can't access its attributes. I have changed the '#div1 img' to 'img' and '.imgr' but with no luck.

我想使用ajax调用从目录加载所有图像,并在添加到html后接受一个图像。 我已成功加载所有图像。 但我的问题是我在jQuery中插入后无法在jQuery中访问它的属性。 p>

如何通过jQuery ajax调用添加图像属性后才能访问它。 / p>

我访问图像src的jQuery代码是 p>

  $(“button”)。click(function(){
 $(“  #div1“)。load(”demo.php“); 
}); 
 $(”#div1 img“)。click(function(){
 console.log($(this).attr(”  src“)); 
});  
  code>  pre> 
 
 

我的html是: p>

 &lt; div id =“div1”&gt;&lt; / div&gt;  
&lt; button&gt;点击此处&lt; / button&gt; 
  code>  pre> 
 
 

我的demo.php是 p>

 &lt  ;?php 
 $ directory = / path / to / folder /; 
 $ images = glob($ directory。“* .jpg”); 
 foreach($ images as $ image)
 {
 echo“  &lt; img class ='imgr'src ='$ image'/&gt;“; 
} 
?&gt; 
  code>  pre> 
 
 

我可以加载图片 到div1元素但我无法访问其属性。 我已将'#div1 img strong>'更改为' img strong>'和' .imgr strong>',但没有运气。 p> DIV>

It's because the data is loaded dynamically.

Change;

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

to

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

You can't bind click event on elements that doesn't exist when the script is loaded. You can change this:

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

to this:

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

You need to have click event on parent div in order to delegate click events to children that are not part of the DOM yet, please check this link on event delegation

Try this instead:

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

I would suggest to use $(document).on("click" , "" , function() {});

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