简体   繁体   中英

Dynamically changing the text of Label on Click in jquery

My web html has following code

<script  src="js/jquery.flexslider.js"></script>
<script  src="js/jquery.rings.js"></script>

Contents of jquery.rings.js are :

$('input[type="image"]').click(function()
{
   $ring = $(this).data('my-info');
   $('label#ringName').text($ring['ringSetName']);
});


/***************************************************/

My Html code is fetching an array of rings

$db = new db();
$rings = $db->query("SELECT * FROM rings");

On runtime i am adding images in a slider as follow

<div class="albums-div">
    <ul class="slides">

        <?php



 foreach($rings as $ring)
          {
             echo '<li> <input type="image" src="' . $ring['ringThumbNailImagePath'] . '" name="checked" value="" data-my-info="' . $ring . '" width="150" height="150" /></li>';
           }   



         ?>
    </ul>
</div>

The problem is , on Clicking the image nothing happens, the JS script seems not to be getting called.

tHE JS function should set the text of a label defined in the code as

What could be the problem?

You need event delegation for dynamically added elements:

$(document).on('click','input[type="image"]',function()
{
  $ring = $(this).data('my-info');
  $('label#ringName').text($ring['ringSetName']);
});

Try to use event delegation for dynamically added elements:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$('body').on('click','input[type="image"]',function()
{
   $ring = $(this).data('my-info');
   $('label#ringName').text($ring['ringSetName']);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM