javascript - 在 JQuery 中创建级联元素

标签 javascript jquery dom

我有以下任务:

create a div with a button dynamically, and this in turn they should create another (div with button), so on.

但是以下代码不起作用:

<div id="M-0">
    <div id="M-0C"></div>
    <input id="add_container" name="add_container" class="cua" type="button" value="Addition Container"  >
</div>

Jquery 代码是:

$(document).ready(function() {
    $(".cua").live("click", function(e){
        var father = $(this).parent();          
        var id_new=father.attr('id')+'.M-';
        var number=0;
        while( $('#'+id_new+number).length ){
            number=number+1;
        }
        id_new=id_new+number;
        alert('here '+id_new);
        $('#'+father.attr('id')+'C').append('<div id="'+id_new+'"><div id="'+id_new+'C"></div><input id="add_container" name="add_container" class="cua" type="button" value="Addition Container" ></div>');
    });
});

单击第一个按钮有效,但下次单击新创建的按钮无效。

最佳答案

尝试使用on()..

$(document).on('click','.cua',function(e){
   var father = $(this).parent();          
    var id_new=father.attr('id')+'.M-';
    var number=0;
   .....

});

fiddle here

关于javascript - 在 JQuery 中创建级联元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16376415/

相关文章:

javascript - 如何将边界添加到位置 :fixed element?

javascript - 在可重用 Polymer 组件内的元素上使用 ID 是否安全?

php - 在php while循环中显示js

php - 在数据库中插入新数据时警告用户

jQuery 验证动态输入数组

jQuery Skitter 幻灯片错误

javascript - 自定义 Angular 指令来动态更改字体大小?

javascript - 我可以使用 javascript 捕获和保存网页的当前状态吗

javascript - 变换缩放后控制图像质量

javascript - DOM:查找 html 元素的当前滚动上下文