[英]how to execute javascript function on dynamically created button's click event.
In my HTML display I have a table showing some names of uploaded files. 在我的HTML显示中,我有一个表格,其中显示了一些上传文件的名称。 and a button to delete that file.
以及删除该文件的按钮。
the names of files are loaded dynamically by Php 文件名由Php动态加载
<tbody>
<?php
foreach ($uploaded_files as $val) {
?>
<tr>
<th>
<a href="delete_this_file/<?php echo $val['id']; ?>" class="delete" data-confirm="Are you sure to delete this item?"><div class="btn btn-danger">Delete</div></a>
</th>
<th>
<?php echo $val['file_name']; ?>
</th>
</tr>
<?php
}
?>
</tbody>
and I have a javascript function in my html head section like this, to confirm did he really want to delete it. 并且我在html头部分中有一个javascript函数,以确认他是否确实要删除它。
$(document).ready(function() {
var deleteLink = document.querySelector('.delete');
deleteLink.addEventListener('click', function(event) {
event.preventDefault();
var choice = confirm(this.getAttribute('data-confirm'));
if (choice) {
window.location.href = this.getAttribute('href');
}
});
});
this is working well only for first button only, and for other buttons it is redirecting to this link href="delete_this_file/ 这仅对第一个按钮有效,对于其他按钮,它将重定向到此链接href =“ delete_this_file /
can some one show me the error in this code. 可以让我看看这段代码中的错误。 I can't figure it out.
我不知道。
Thank You very Much 非常感谢你
Take a look at this link: https://api.jquery.com/on/ 看一下此链接: https : //api.jquery.com/on/
the on
method will bind events to dynamically created objects on
方法会将事件绑定到动态创建的对象
$(document).on("click", ".delete", function() {
//your code here
});
When you use the regular addEventListener, it binds it only to the current matching elements on the DOM, any matching element created after this point, will not be binded 当您使用常规的addEventListener时,它仅将其绑定到DOM上的当前匹配元素,此后创建的任何匹配元素都不会被绑定
<tbody>
<?php
foreach ($uploaded_files as $val) {
?>
<tr>
<th>
<a style="cursor:pointer" onclick="deleteFun(<?php echo $val['id']; ?>)" class="delete"><div class="btn btn-danger">Delete</div></a>
</th>
<th>
<?php echo $val['file_name']; ?>
</th>
</tr>
<?php
}
?>
</tbody>
<script>
function deleteFun(id){
var choice = confirm("Are you sure to delete this item?");
if (choice) {
window.location.href = "delete_this_file/"+id;
}
}
<script>
just Try this, more minimized answer 只是尝试一下,答案最小化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.