简体   繁体   English

Javascript可在控制台上运行,但不能在onclick事件上运行

[英]Javascript working on console, but not onclick event

I'm fairly new with JavaScript, I'm trying to give access to users to update products stock for WooCommerce. 我对JavaScript不太熟悉,我想让用户访问以更新WooCommerce的产品库存。 I've made "Update" button to run the script, but it won't run, the page only refreshes. 我已经单击“更新”按钮来运行脚本,但是它不会运行,页面只会刷新。 But when I execute the script from console, it works (eg. js_update_stock('20');) 但是当我从控制台执行脚本时,它可以工作(例如js_update_stock('20');)

I'm working by modifying existing plugin for WordPress, so I'm sorry if the codes are a bit scattered. 我正在通过修改WordPress的现有插件来工作,所以对不起,如果代码有点分散。 If you need anything else, please let me know. 如果您还有其他需要,请告诉我。

HTML side of things: 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>

I put this script on the same page: 我将此脚本放在同一页面上:

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 Callback function: 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
}

Any help is appreciated, as this has been bugging me for 2 days now. 感谢您的帮助,因为这已经困扰了我2天了。 Thank you. 谢谢。

By default a button is of type submit so it's submitting your form, thats why your page refreshes. 默认情况下,按钮的类型为“提交”,因此它正在提交表单,这就是页面刷新的原因。

You want to define button type as button so form doesn't submit. 您想将按钮类型定义为按钮,以便表单不提交。

<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>

The page is refreshing because I guess the button you are using is in a form. 该页面令人耳目一新,因为我猜您正在使用的按钮位于表单中。 So when you click on it, it will launch the request for the form and leave the page. 因此,当您单击它时,它将启动对表单的请求并离开页面。

So to prevent that, you will just need to add the click event to your function and cancel it before the page has unload : 因此,为防止这种情况,您只需要在函数卸载之前将click事件添加到函数中并取消它即可:

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

And for javascript : 对于javascript:

function js_update_stock(e, product_id) {
    e.preventDefault();
    // more code...

Javascript event prevent default on W3schools Javascript事件阻止W3schools上的默认设置

I hope this solved your problem ;) 我希望这可以解决您的问题;)

For most of the new browsers, default type of button element is "Submit". 对于大多数新浏览器,按钮元素的默认类型为“提交”。 That means, when click on it, your form will get submitted before calling your "onclick" function. 这意味着,单击它时,将在调用“ onclick”函数之前提交表单。 Also, in your form you may not have specified action attribute, and that's why form is submitting to self. 另外,您的表单中可能没有指定的动作属性,这就是表单向自身提交的原因。

You can specify type attribute for your button element to "button" specifically and it will now call to your "onclick" function. 您可以将按钮元素的type属性指定为“ button”,现在它将调用“ onclick”功能。

For more information on button default type according to browser, visit : What is the default button type? 有关根据浏览器的按钮默认类型的更多信息,请访问: 默认按钮类型是什么?

Instead of button tag, you can use : 除了按钮标签,您可以使用:

<a href='javascript:void(0);' id='updateBtn' class='btn btn-default'>Update</a>

$(document).ready(function () {
  $('#updateBtn').on('click', function () {
    // Make AJAX call here.  
    // Your logic will come here.
    $.ajax({
      url: 'Add url here',
      data: 'Add data which is need to be update in json',
      type: 'POST',
      dataType: 'json',
      success: successCallback,
      complete: completeCallback,
      error: errorCallback
    })
  });

  var successCallback = function () {
                         // AJAX success callback
                       }

  var completeCallback= function () {
                         // AJAX complete callback
                       }
  var errorCallback= function () {
                         // AJAX error callback
                       }
});

NOTE: Also make sure you are not redirecting from backend(PHP) and just giving back response with statusCode. 注意:还请确保您没有从backend(PHP)重定向,而只是通过statusCode返回响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM