0
我使用包含對象的數組創建了一些動態內容。現在,我的動態內容有一個按鈕,可以幫助我在點擊時從「myData」數組中獲取相應的對象。通過點擊動態按鈕來抓取相應的對象
我很困惑我如何從myData數組中獲取相應的對象。
你能幫我解決嗎?
下面的代碼:
var myData = [
{
\t 'car': 'Ford',
\t 'color': 'Black',
\t 'model': 'Figo' \t \t \t
}, {
\t 'car': 'Ford',
\t 'color': 'Red',
\t 'model': 'Endeavour' \t \t \t
},{
\t 'car': 'Jaguar',
\t 'color': 'White',
\t 'model': 'F-Type' \t \t \t
},
];
$(document).ready(function(){
$('#createData').click(function(){
\t myData.forEach(function(obj){
\t $('.container').append(
\t \t $('<div>').addClass('parent').append(
\t \t $('<div>').append(
\t \t \t $('<label>').text('Car: '),
\t \t \t $('<span>').text(obj.car)
\t \t ),
\t \t $('<div>').append(
\t \t \t $('<br /><label>').text('Model: '),
\t \t \t $('<span>').text(obj.model)
\t \t ),
\t \t $('<br /><button>').text('Click Me').addClass('getData')
\t \t)
\t )
\t });
}); \t \t \t
});
$(document).on('click', '.getData', function(obj){
var myColor = $(this);
console.log(obj);
});
.parent {
border: 1px solid lightgrey;
border-radius: 5px;
background-color: skyblue;
height: 100px;
margin-top: 5px;
padding: 10px; \t \t \t
}
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<button id="createData">Create Data</button>
<div class="container">
</div>
非常感謝..但必須有一個選項來添加點擊事件動態按鈕,其中我可以傳遞整個對象作爲參數... – Sunny