2017-11-10 12 views
0

以下は、クローンオブジェクトにclickイベントをアタッチしようとしていたサンプルコードですが、それはできませんでした。オブジェクトへのclickイベント。コードをチェックして、あなたの貴重な提案jqueryを使用してクローンオブジェクトにclickイベントを追加できません

$(document).ready(function(){ 
 
    var documentSelector = $('.clone-block') 
 
    var arrayOfObjects = [{ 
 
    \t name: "William", 
 
     gender: "Male", 
 
     dateofbirth: "01-01-2017" 
 
    }, 
 
    { 
 
    \t name: "Michale", 
 
     gender: "Female", 
 
     dateofbirth: "01-01-2018" 
 
    }, 
 
    { \t 
 
    \t name: "John", 
 
     gender: "male", 
 
     dateofbirth: "01-01-2019" 
 
    }, 
 
    { 
 
    \t name: "tom", 
 
     gender: "male", 
 
     dateofbirth: "01-01-2020" 
 
    }]; 
 
    
 
    $.each(arrayOfObjects, function (ind, user){ 
 
    \t 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() { 
 
    \t 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" > 
 
\t <p>Username : <span></span></p> 
 
</div> 
 
<div class="link-p" ></div> 
 
</body> 
 
</html>

答えて

1
$('.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); 
} 
関連する問題