我正在制作一个管理页面,该页面显示了使用(我使用eJS用于模板渲染引擎(的帖子列表
<table>
<tr>
<th>Nama</th>
<th>Watever</th>
</tr>
<% xprojects.forEach(function(data) { %>
<tr>
<td><%= data.name %></td>
<td><%= data.desc %></td>
<td><a href="javascript:void(0);"
onclick="hello();">Edit</a></td>
<td>Delete</td>
</tr>
<% }) %>
</table>
编辑按钮(链接(在另一个文件中调用JavaScript函数
function hello() {
alert('This should show the "Name" of the table row which button clicked');
}
我怎么知道哪个表行的按钮调用hello((函数,然后从表行中检索数据(例如'name'列(
像vinod一样,我会附上一个事件侦听器,而不是使用inline-js( onclick
(
在您的html中,每个锚定标签都可以具有数字属性和一个类editlink
:
<a number="1" class="editlink">Edit</a>
在香草JS中:
// Select all elements that have the class '.editlink'
let editlinks = document.querySelectorAll('.editlink');
// for-loop for each editlink
editlinks.forEach(function(editlink) {
// add event-listener with click-event
editlink.addEventListener('click', function(e) {
// e.target is the clicked element
let clickedElement = e.target;
let clickedElementNumberAttribute = clickedElement.getAttribute('number');
alert('You clicked number ' + clickedElementNumberAttribute);
})
});
或这里:https://jsfiddle.net/bblumenfelder/oaajf8ld/
我认为这会对您有所帮助。
<script>
$(function () {
$('table').on('click', function (e) {
var x = $(e.target);
alert($(x.parents().find('tr').find('td,th')[0]).text());
});
});
</script>
访问http://jsfiddle.net/gcq2019k/1/这里
html add:
onclick="hello('"+ data.name + "');"
然后在JS中:
function hello(name) {
alert('This should show the name of the table row which button clicked: ' + name);
}