Javascript函数(与ajax)不工作时,onclick事件



Onclick按钮事件不与ajax.js函数一起工作。我不知道问题是什么,也不知道解决问题的办法。下面是我的代码:

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上运行snippet的沙箱中,这将导致错误,但您可以使用控制台工具检查网络流量,并观察AJAX请求被正确发送-data-id属性在AJAX有效负载中分配。

最新更新