jQuery和WordPress – 脚本不起作用

我试图将一些jquery实现为我正在创建的wp插件。

在我的主题的functions.php中,我有以下代码:

function load_jquery() { // only use this method is we're not in wp-admin if ( !is_admin() ) { // deregister the original version of jQuery wp_deregister_script('jquery'); wp_deregister_script('jquery-ui-slider'); wp_deregister_style('jquery-ui-style'); // discover the correct protocol to use $protocol='http:'; if($_SERVER['HTTPS']=='on') { $protocol='https:'; } // register the Google CDN version wp_register_script('jquery', $protocol.'//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js', false, '1.10.2'); wp_register_script('jquery-ui-slider', $protocol.'//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js', false, '1.10.3'); wp_register_style('jquery-ui-style', $protocol.'//code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css', false ); // add it back into the queue wp_enqueue_script('jquery'); wp_enqueue_script('jquery-ui-slider'); wp_enqueue_style('jquery-ui-style'); } } add_action('wp_enqueue_scripts', 'load_jquery'); 

然后在其中一个插件文件中,我通过函数和add_action(’wp_head’,’functions_name’)输出以下内容;

 echo '  jQuery(function($) { $( "#slider-range" ).slider({ range: true, min: 0, max: 500, values: [ 75, 300 ], slide: function( event, ui ) { $( "#amount" ).val( "$" + ui.values[ 0 ] + " - $" + ui.values[ 1 ] ); } }); $( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) + " - $" + $( "#slider-range" ).slider( "values", 1 ) ); }); '; 

尽管我可以看到在实际脚本之前加载的jquery,但仍然没有任何效果。

有任何想法吗? 如果我跳过wp_enqueue_script部分并超过themefile的header.php中的所有内容,它就可以工作。

您应该使用jQuery(document).ready(function($)包装脚本,因为可以加载jquery对象,但您也需要jquery-ui脚本。

 '; 

最大的问题是wordpress 冲突情况,为了让你的脚本工作,你需要用’jQ​​uery’替换你在jQuery中使用的所有‘$’符号。 每个好的wordpress主题开发都知道这一点,wordpress与你的代码冲突,所以你需要适应。

示例:

  jQuery(document).ready(function($){ jQuery( "#slider-range" ).slider({ etc etc )}; )}; 

我希望我是对的,因为我有同样的问题,做到了,它已经解决了。 🙂