-2

I have a simple js script which gets backgrounds of the following elements:

    <ul class="vk_image_grid">
      <li style="background-image: url(https://name.com/image1.jpg)" class="block">
      </li>
      <li style="background-image: url(https://name.com/image2.jpg)" class="block">
      </li>
      <li style="background-image: url(https://name.com/image3.jpg)" class="block">
      </li>
     </ul>
<script>
 $("ul li").on( "click", function() {
  var bg = $(this).css('background-image');
  alert(bg);
</script>

It works perfectly with the first two li which are generated by php. But it doesn't show the background of the third li which is generateed by another jQuery script. How can I fix the issue?

1 Answers1

-3

The third li element seems to be generated after the $("ul li") has been run. Therefore the event handler won't be attached to the third li element.

Either you make sure the li is generated before you iterate the li's to attach the event handler or you add the event handler in the method where you generate the new li element.

To help you more precisely you need to provide more details of your code.

Sven Tschui
  • 1,377
  • 8
  • 20