如何为动态生成的子div附加事件处理程序? [英] How to attach an Event Handler for dynamically generated Child divs?

查看:64
本文介绍了如何为动态生成的子div附加事件处理程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个页面,其中包含2个Div容器(Left和Right). PartsList页面具有5个动态生成的DIVS. 自定义页面有5个动态生成的DIVS. 标识为"layout"的div不会被jQuery .on()识别.请帮忙.谢谢您的时间:).

I have a page with 2 Div containers ( Left and Right ). PartsList page has 5 dynamically generated DIVS. Custom page has 5 dynamically generated DIVS. The div with id "layout" isnt getting recognized with the jQuery .on(). Please help. Thank you for you time :).

<script type="text/javascript" src="js/jquery.js">
</script>

<script type="text/javascript">

$(function() {

    $(".left").load("PartsList.php",function() {alert("success");});

    $(".right").load("Custom.php", function() {alert("success");});

        $("#layout").children().on({click: function() {
            alert($(this).attr('id'));

          }
 });    

});
</script>

<body>
<div class="main">

<div class="left">
//Load Left page.

</div>
<div class="right">

//Load Structure page.
</div>

</div>
</body>


</html>

PartsList

PartsList

<?php


for ($x = 1; $x < 6; $x++)
{

   $divs = <<<here
   <div id = 'div$x' class = 'list'><strong>Div: $x</strong></div>
   here;
   echo $divs;
 }

?>

自定义

<?php

echo '<div id="layout">';

for ($y = 0; $y < 5; $y++)
{
        echo "<div id='x$y' style='
        position: absolute;
        width: 200px;
        height: 100px;
        top: ".(100 * $y)."px;
        border: 2px solid blue;
        cursor: pointer;
        '></div>";
}

echo '</div>';

?>

推荐答案

在jQuery 1.7+中使用

in jquery 1.7+ use on like

$(document).on('click','dynamicElement',function(e){

 //handler code here
});

在早期版本中的

使用 delegate

in the earlier versions use delegate

$(document).delegate('dynamicElement','click',function(e){

 //handler code here
});

您可以将document替换为动态生成的元素的父元素

you can replace the document with parent element of the dynamically generated element

这篇关于如何为动态生成的子div附加事件处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆