Javascript Handlebar和js:在for循环内部分配不同的id值,并在循环外部引用它们
在我的网页中,我正在使用手柄填充表格,并从数据库中获取值:Javascript Handlebar和js:在for循环内部分配不同的id值,并在循环外部引用它们,javascript,html,handlebars.js,Javascript,Html,Handlebars.js,在我的网页中,我正在使用手柄填充表格,并从数据库中获取值: <table> <tbody id="myDiv"> {{# each alarms}} <tr class="row100 body"> <td class="cell100 column1"><a href="#" id="btn_exp">{{ this.alm_id }}</a></td> <td c
<table>
<tbody id="myDiv">
{{# each alarms}}
<tr class="row100 body">
<td class="cell100 column1"><a href="#" id="btn_exp">{{ this.alm_id }}</a></td>
<td class="cell100 column2><a href="#">{{ this.message }}</a></td>
<td class="cell100 column3"><a href="#">{{ this.level }}</a></td>
</tr>
{{/each}}
</tbody>
</table>
{{{#每个警报}
使用类的方法比IDs更有效。类是将标识符应用于类似元素的好方法。在这种情况下,您需要一种方法将单击事件应用于多个btn exp
要将数据传递给元素,请利用元素上的To data属性。您可以将所需的任何数据从句柄栏传递到属性中,稍后在JavaScript中进行访问
<table>
<tbody id="myDiv">
{{# each alarms}}
<tr class="row100 body">
<td class="cell100 column1">
<!-- Class will be used to select all .btn_exp and from their events you can access the unique data -->
<a href="#" class="btn_exp" data-alm-id="{{this.alm_id}}">
{{ this.alm_id }}
</a>
</td>
<td class="cell100 column2><a href="#">{{ this.message }}</a></td>
<td class="cell100 column3"><a href="#">{{ this.level }}</a></td>
</tr>
{{/each}}
</tbody>
</table>
有关querySelector()
和queryselectoral()
在此处签出MDN的更多信息这正是我想要的!谢谢只是一张你写的querySelectorAll而不是querySelectorAll的便条。
<table>
<tbody id="myDiv">
{{# each alarms}}
<tr class="row100 body">
<td class="cell100 column1">
<!-- Class will be used to select all .btn_exp and from their events you can access the unique data -->
<a href="#" class="btn_exp" data-alm-id="{{this.alm_id}}">
{{ this.alm_id }}
</a>
</td>
<td class="cell100 column2><a href="#">{{ this.message }}</a></td>
<td class="cell100 column3"><a href="#">{{ this.level }}</a></td>
</tr>
{{/each}}
</tbody>
</table>
var modal_exp = document.getElementById('myModal_explanatory');
var btn_exp = document.querySelectorAll('.btn_exp'); // This returns a NodeList of the .btn_exp objects
var span_exp = document.getElementById("close_exp");
span_exp.onclick = function() { modal_exp.style.display = "none"; }
btn_exp.forEach(function(button) {
button.addEventListener('click', function(event) {
// Through the event object you can get the unique instance of .btn_exp that you clicked
var button = event.currentTarget
modal_exp.style.display = "block";
// If you wanted to get the data-alm-id value for this specific button you can access it like this
var button_alm_id = button.dataset.almId // dashes are converted to Camel case
// ... Do what ever you want with this value
});
});