无法使用jquery将click事件添加到克隆对象

时间:2017-11-10 18:21:46

标签: jquery binding onclick onclicklistener jquery-clone

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



$(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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

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

您正在将对象转换为html,并将其附加到dom上,而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);
}