在特定页面wordpress上运行内联javascript

时间:2018-06-03 16:16:24

标签: javascript wordpress woocommerce

我想只在WooCommerce中的简单产品页面上运行jQuery代码。

这是我的代码:

jQuery(document).ready(function( $ ){

let qty = document.getElementById('qty');

qty.onblur = function(){
  let val  = this.value; // Current Value
  let step = this.getAttribute('step'); // Get step instead of hard coding it

  let roundDown = (val - (val % step)).toFixed(2);
  let roundUp   = (parseFloat(roundDown) + parseFloat(step)).toFixed(2);

  this.value = roundUp;
}

});

如何在Javascript代码中实现此目的?

2 个答案:

答案 0 :(得分:1)

如果您的代码导致错误,因为在其余页面上没有id为“qty”的元素,您可以将此代码添加到主js文件中,如下所示:

$(function() {

  if ( $('#qty').length ) {
     let qty = document.getElementById('qty');

     qty.onblur = function(){
       let val  = this.value; // Current Value
       let step = this.getAttribute('step'); // Get step instead of hard coding it

       let roundDown = (val - (val % step)).toFixed(2);
       let roundUp   = (parseFloat(roundDown) + parseFloat(step)).toFixed(2);

       this.value = roundUp;
     }
  }

});

或者您可以在结束标记之前将此代码添加到footer.php,添加输出条件:

<?php is_singular( 'products' ) :?> <!--change this to your need - https://codex.wordpress.org/Conditional_Tags -->
<script>
jQuery(document).ready(function( $ ){

let qty = document.getElementById('qty');

qty.onblur = function(){
  let val  = this.value; // Current Value
  let step = this.getAttribute('step'); // Get step instead of hard coding it

  let roundDown = (val - (val % step)).toFixed(2);
  let roundUp   = (parseFloat(roundDown) + parseFloat(step)).toFixed(2);

  this.value = roundUp;
}

});
</script>
<?php endif;?>

答案 1 :(得分:0)

您可以将Javascript添加到WordPress的最佳方式

  1. 将上述代码保存到名为 only-page.js 的文件中,并上传到您的主题文件夹。

  2. 将以下代码添加到主题的functions.php文件中:

    function f50668438_enqueue_script() {
        wp_enqueue_script( 'only-page-custom-script', get_stylesheet_directory_uri() . '/only-page.js', array( 'jquery' ) );
    }
    
    if( is_page(2) ){ // page ID or page slug here
        add_action( 'wp_enqueue_scripts', 'f50668438_enqueue_script' );
    }
    
  3. 完成