简体   繁体   English

动态更改jquery中单击时的Label文本

[英]Dynamically changing the text of Label on Click in jquery

My web html has following code 我的网页HTML包含以下代码

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

Contents of jquery.rings.js are : jquery.rings.js的内容是:

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


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

My Html code is fetching an array of rings 我的HTML代码正在获取一个环数组

$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. 问题是,单击图像后没有任何反应,似乎没有调用JS脚本。

tHE JS function should set the text of a label defined in the code as JS函数应将代码中定义的标签文本设置为

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']);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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