【问题标题】:How to attach an Event Handler for dynamically generated Child divs?如何为动态生成的子 div 附加事件处理程序?
【发布时间】:2012-06-02 08:51:22
【问题描述】:

我有一个包含 2 个 Div 容器( Left 和 Right )的页面。 PartsList 页面有 5 个动态生成的 DIVS。 自定义页面有 5 个动态生成的 DIVS。 id 为“layout”的 div 没有被 jQuery .on() 识别。请帮忙。谢谢你的时间:)。

<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>

零件清单

<?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>';

?>

【问题讨论】:

  • 经过一段时间的测试。我发现在#layout 指令之后页面正在加载。有人知道为什么会这样吗?

标签: php jquery dynamic


【解决方案1】:

在 jquery 1.7+ 中使用 on 喜欢

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

 //handler code here
});

在早期版本中使用delegate

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

 //handler code here
});

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

【讨论】:

  • 该方法不起作用。您能否为我提供一个包含我的代码的工作示例。这真的很有帮助。谢谢你:)
  • 你的回答是对的 :)。对不起,尽管引用了 <.>
【解决方案2】:

来自 Jquery 在线手册:

.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )

url:包含请求发送到的 URL 的字符串。

data:随请求发送到服务器的映射或字符串。

complete(responseText, textStatus, XMLHttpRequest)请求完成时执行的回调函数。

您可能需要将 .on 函数作为 Custom.php 页面的 .load 回调。

类似这样的例子:

$(function() {

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

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

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

          }
 });
 });    

});

【讨论】:

    【解决方案3】:

    我认为你的 .on() 函数的语法有误,应该是这样的:

    $('document').on('click', '#layout > div', function() {
        alert($(this).attr('id'));
    });
    

    您绑定到文档,当用户单击布局中的子 div 时,事件会“冒泡”DOM 到它被捕获的文档。

    【讨论】:

    • 我试过你的方法,但它也不起作用。出于某种原因,当我使用 firebug 并在控制台中测试命令时,它可以工作。但在页面上,它的行为就好像该元素从未存在过一样。
    • 每个甚至想到使用$(this).attr('id') 的人都应该受到预防性的打击......同样将alert() 用作调试工具。
    【解决方案4】:

    好的。无论如何我找到了答案。对于那些在想为什么它不起作用的人。这是因为愚蠢的报价。

    $("document") 应该是 $(document),因为 document 不是标签

    多田就是这样。

    叹息。

    感谢大家的帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-19
      相关资源
      最近更新 更多