我使用jQuery的循环,并创建循环以创建一些具有值的框.
问题是,我创建了一个盒子,对于这个盒子,我从数组中获取值,并且对于每个值,我都必须采取行动,例如调用allert.
我的代码:
var mokData = [
{ category: "Material",id: 'Code0-1',name: 'Brakedown of machine' },{ category: "Material",{ category: "Tool",name: 'Brakedown of line' },name: 'Brakedown of line' }
];
$.each(mokData,function (i) {
var templateString = '<article class="card"><h2>' + mokData[i].category + '</h2><p>' + mokData[i].name + '</p><p>' + mokData[i].id + '</p><button class="tes">Start</button></article>';
$('#favoriteCards').append(templateString);
});
$(".tes").on("click",function () {
alert("Click");
});
.cards {
margin: -1rem;
}
.card {
width: 220px;
float: left;
margin: 1rem;
border: 1px solid #d3d3d3;
padding: 20px;
border-radius: 5px;
background-color: white;
}
@supports (display: grid) {
.cards {
margin: 0;
}
.cards {
display: grid;
grid-template-columns: repeat(auto-fit,minmax(300px,1fr));
grid-gap: 1rem;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main class="cards">
<div id="favoriteCards"></div>
</main>
如您所见,我对按钮有操作,但是这不正确,因为我希望使用数组中的数据为单独的按钮单独发出警报.
最佳答案
将要作为警报的数据添加为custom attribute(
data-*
)到元素,并在需要警报时获取它.除了jQuery.each
中的回调外,第二个参数是添加第二个参数(甚至可以使用)的元素,并将其用于引用元素,而不是通过索引获取.
var mokData = [{"category":"Material","id":"Code0-1","name":"Brakedown of machine"},{"category":"Material",{"category":"Tool","name":"Brakedown of line"},"name":"Brakedown of line"}];
$.each(mokData,function() {
var templateString = '<article class="card"><h2>' + this.category + '</h2><p>' + this.name + '</p><p>' + this.id + '</p><button class="tes" data-alert="' + this.name + '">Start</button></article>';
$('#favoriteCards').append(templateString);
});
$(".tes").on("click",function() {
alert($(this).data('alert'));
});
.cards {
margin: -1rem;
}
.card {
width: 220px;
float: left;
margin: 1rem;
border: 1px solid #d3d3d3;
padding: 20px;
border-radius: 5px;
background-color: white;
}
@supports (display: grid) {
.cards {
margin: 0;
}
.cards {
display: grid;
grid-template-columns: repeat(auto-fit,1fr));
grid-gap: 1rem;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main class="cards">
<div id="favoriteCards"></div>
</main>