gpt4 book ai didi

Javascript 在控制台上工作,但不是 onclick 事件

转载 作者:行者123 更新时间:2023-11-30 14:30:18 25 4
gpt4 key购买 nike

我对 JavaScript 相当陌生,我正在尝试授予用户访问权限以更新 WooCommerce 的产品库存。我制作了“更新”按钮来运行脚本,但它不会运行,页面只会刷新。但是当我从控制台执行脚本时,它起作用了(例如 js_update_stock('20');)

我正在修改现有的 WordPress 插件,所以如果代码有点零散,我很抱歉。如果您还需要什么,请告诉我。

HTML 方面的事情:

<input type="number" id="stock'. $postid . '" name="stock'. $postid .'" value="'. get_post_meta( $postid, '_stock', true ) .'">

<button class="button button-primary" style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" onclick="js_update_stock(\''. $postid .'\')">'. __('Update','update_button') .'</button>

我把这个脚本放在同一个页面上:

echo '<script type="text/javascript">
function js_update_stock(product_id) {
var isnum = /^\d+$/.test(document.getElementById("stock" + product_id).value);
if(isnum){
if(confirm("Do you really want to update the stock of this product?")){
var data = {
action: \'update_stock\',
security: \'' . $ajax_nonce . '\',
id: product_id,
stock: document.getElementById("stock" + product_id).value
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
if(response == \'true\'){
location.reload(true);
}
});
}
else{
// do nothing
}
}
else{
alert("Please enter a valid stock quantity");
}
}
</script>';

AJAX 回调函数:

add_action('wp_ajax_update_stock', 'update_stock_callback');
function update_stock_callback() {
check_ajax_referer( 'blahblah', 'security' );
if(isset($_POST['id'])){
$id = intval( $_POST['id'] );
$stock = intval( $_POST['stock'] );
wc_update_product_stock( $id, $stock );
echo 'true';
}
else{
echo 'false';
}
die(); // this is required to return a proper result
}

感谢任何帮助,因为这已经困扰我 2 天了。谢谢。

最佳答案

默认情况下,按钮的类型为提交,因此它正在提交您的表单,这就是您的页面刷新的原因。

您想将按钮类型定义为按钮,这样表单就不会提交。

<button type="button" class="button button-primary" style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" onclick="js_update_stock(\''. $postid .'\')">'. __('Update','update_button') .'</button>

关于Javascript 在控制台上工作,但不是 onclick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51300307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com