dongpan1365 2015-05-18 22:27
浏览 75

如何将简单的查询字符串jQuery脚本添加到WordPress

I'm trying to add the ability to populate fields dynamically via query strings in WordPress. I've created dm_email.js containing the following:

    jQuery(function( $ ){
    
    //grab the entire query string
    var query = document.location.search.replace('?', '');
    
    //extract each field/value pair
    query = query.split('&');
    
    //run through each pair
    for (var i = 0; i < query.length; i++) {
    
    //split up the field/value pair into an array
      var field = query[i].split("=");
      
    //target the field and assign its value
      $("input[name='" + field[0] + "'], select[name='" + field[0] + "']").val(field[1]);
    
    } 
    });

and placed this in mytheme/js/dm_email.js

In my functions.php I've add the following:

add_action( 'wp_enqueue_scripts', 'dm_query_string' );
    function dm_query_string() {
    wp_enqueue_script(
        'dm_query',
        get_template_directory_uri() . '/js/dm_email.js', 
        array('jquery') 
    );
    }

But the expected functionality keeps failing. If I add the following to wp_head() I get the expected functionality but of course I also get a lot of issues with other scripts/plugins:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
    
    //grab the entire query string
    var query = document.location.search.replace('?', '');
    
    //extract each field/value pair
    query = query.split('&');
    
    //run through each pair
    for (var i = 0; i < query.length; i++) {
    
      //split up the field/value pair into an array
      var field = query[i].split("=");
      
      //target the field and assign its value
      $("input[name='" + field[0] + "'], select[name='" + field[0] + "']").val(field[1]);
    
    }
  });
</script>

I'm at a loss as to where I've gone wrong with either the js or functions.php any help or guidance greatly appreciated.

</div>
  • 写回答

2条回答 默认 最新

  • dongma2388 2015-05-19 08:55
    关注

    Try to place your script into footer and not to head. You can do the followig:

    First be sure you enqueued jQuery.

    Changes in functions.php:

    wp_enqueue_script(
        'dm_query',
        get_template_directory_uri() . '/js/dm_email.js', 
        array('jquery'),
        '1.0.0',
        true
    );
    

    Changes in Your js:

    (function($){ /* Your Code */ })(jQuery);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算