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

在特定页面wordpress上运行内联javascript,javascript,wordpress,woocommerce,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 instea

我只想在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代码中实现这一点?

将Javascript添加到WordPress的最佳方法
  • 将上述代码保存到名为only page.js的文件中,然后上载到主题文件夹

  • 将以下代码添加到主题的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' );
    }
    
  • 完成


  • 如果您的代码导致错误,因为在剩余页面上没有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;?>
    
    
    jQuery(文档).ready(函数($){
    让qty=document.getElementById('qty');
    qty.onblur=函数(){
    让val=this.value;//当前值
    让step=this.getAttribute('step');//获取步骤而不是硬编码它
    让舍入=(val-(val%步长)).toFixed(2);
    设roundUp=(parseFloat(roundDown)+parseFloat(step)).toFixed(2);
    this.value=roundUp;
    }
    });
    
    jQuery是JavaScript。你到底在问什么?你不想使用jQuery?还是怎样