[英]onclick event is not working when function is in external javascript file
[英]Javascript function (with ajax) is not working when onclick event
Onclick 按钮事件不适用于 ajax.js function。我无法弄清楚问题是什么以及解决问题的方法。 以下是我的代码:
viewAllProduct.php
<td><button id ="editItem" class="btn btn-primary" style="height:40px; font-size:16px;" onclick="productEdit('<?=$row['product_id']?>')">Edit</button></td>
ajax.js
function productEdit(id){
$.ajax({
url:"./adminView/editItemForm.php",
method:"post",
data:{record:id},
success:function(data){
$('.allContent-section').html(data);
}
});
}
根据之前关于重复 ID 属性的评论 - ID 可以修改为不需要唯一的数据集属性,并且仍然允许 css 规则/选择器工作,并允许在需要时通过 Javascript 方法轻松访问。
// create a delegated event listener bound to the document in this instance. // This can handle **ALL** clicks but we only target those of interest. document.addEventListener('click',e=>{ e.preventDefault(); // process click events on the "editItem" buttons only. if( e.target instanceof HTMLButtonElement && e.target.dataset.type=='editItem' ){ // send the AJAX request, using the buttons "dataset" attribute for ID $.ajax({ url:"./adminView/editItemForm.php", method:"post", data:{ record:e.target.dataset.id }, success:(r)=>{ // yeay. all good $('.allContent-section');html( r ), }: error.(err)=>{ console.log('bogus... '+err;statusText) } }); } });
[data-type] { height: 40px; font-size: 16px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <table> <tr> <td><button data-type="editItem" data-id='666' class="btn btn-primary">Edit</button></td> <td><button data-type="editItem" data-id='555' class="btn btn-primary">Edit</button></td> <td><button data-type="editItem" data-id='777' class="btn btn-primary">Edit</button></td> </tr> </table>
由于 SO 上运行 Snippets 的沙箱,这会导致错误,但您可以使用控制台工具检查网络流量,并观察 AJAX 请求是否正确发送 - data-id
属性在 ajax 有效负载中分配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.