无法使用 jquery 将点击事件添加到克隆的对象

Unable to add click event to a cloned object using jquery

下面是示例代码,我试图将点击事件附加到克隆的对象,但我做不到,我已经尝试了很多,但我无法将点击事件附加到对象。请检查代码并提出宝贵建议

$(document).ready(function(){
    var documentSelector = $('.clone-block')
    var arrayOfObjects = [{
     name: "William", 
        gender: "Male",
        dateofbirth: "01-01-2017"
    }, 
    {
     name: "Michale", 
        gender: "Female",
        dateofbirth: "01-01-2018"
    }, 
    { 
     name: "John", 
        gender: "male",
        dateofbirth: "01-01-2019"
    },
    {
     name: "tom", 
        gender: "male",
        dateofbirth: "01-01-2020"
    }];
    
    $.each(arrayOfObjects, function (ind, user){
     var clonedObject = documentSelector.clone(true, true);       
        clonedObject.find('span').on('click', alertWhenClicked.bind(user));
        clonedObject.find('span').text(user.name);
        $('.link-p').append(clonedObject.html());
    });
    
    function alertWhenClicked () {
     alert(this.dateofbirth);
    }
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div class="clone-block" >
 <p>Username : <span></span></p>
</div>
<div class="link-p" ></div>
</body>
</html>

$('.link-p').append(clonedObject.html());

您正在将对象转换为 html 并将其附加到 dom,它不会有任何事件绑定。脱下.html()

顺便说一句,您应该研究委托绑定,这样您就不必对所有这些元素都进行事件绑定。

$.each(arrayOfObjects, function (ind, user){
    var clonedObject = documentSelector.clone(true, true);
    //put the user on the element as a data object for easy reference
    clonedObject.data('user', user);
    clonedObject.find('span').text(user.name);
    $('.link-p').append(clonedObject);
});

//delegate bind the click event to the parent for the future child elements
$('.link-p').on('click', '.clone-block', alertWhenClicked);

function alertWhenClicked () {
    alert($(this).data('user').dateofbirth);
}