【问题标题】:I cannot apply javascript to Wordpress. Can you help me?我无法将 javascript 应用于 Wordpress。你能帮助我吗?
【发布时间】:2019-06-07 13:38:48
【问题描述】:

我在 https://www.youtube.com/watch?v=t0swZkgTQnk 学习了本教程 至此解释如何将 javascript 添加到 wordpress。但是当我启动页面时,在源页面中,.js 文件被重新定位到其他地方。

我将 .js 文件放在“C:\Users\xxxxx\Documents\Websites\www.testsite.dev.cc\wp-content\themes\profile-lite\js”中,但在页面源中,文件列在“http://www.testsite.dev.cc/wp-content/themes/profile-lite/style.cssjs/script.js?ver=3.2.1”中。

我尝试在“C:\Users\xxxxx\Documents\Websites\www.testsite.dev.cc\wp-content\themes\profile-lite”中创建一个文件夹,其中包含“style.cssjs”文件夹以查看如果文件可以读取但没有任何运气!

在我的 function.php 文件中,这是我的代码:

function cool_scripts(){

    wp_enqueue_script('cool-stuff', get_stylesheet_uri(). 'js/script.js', array('jquery'), '3.2.1', false);
}
    add_action('wp_enqueue_scripts','cool_scripts');

在我的 script.js 文件中,这是我的代码:

//with class div
		jQuery(document).ready(function(){
			$(".videowidth").hover(function(){
				$(this).children("video")[0].play();
			},
			function(){
			$(this).children("video")[0].pause();
			});
		});
		// Without id and class div
		/*$(document).ready(function(){
			$("video").hover(function(){
				$(this)[0].play();
			},
			function(){
			$(this)[0].pause();
			});
		});*/

我希望文件能够加载,但控制台中出现此错误。

(索引):103 GET http://www.testsite.dev.cc/wp-content/themes/profile-lite/style.cssjs/script.js?ver=3.2.1 net::ERR_ABORTED 404(未找到) enter image description here

【问题讨论】:

    标签: javascript jquery wordpress


    【解决方案1】:

    我找到了!!

    (function($) {
        $(function() {
            $('video').hover(function() {
                this.play();
            }, function() {
                this.pause()
            });
        });
    })(jQuery);
    

    【讨论】:

      【解决方案2】:

      您需要使用get_stylesheet_directory_uri() 而不是get_stylesheet_uri()

      function cool_scripts(){
      
          wp_enqueue_script('cool-stuff', get_stylesheet_directory_uri(). 'js/script.js', array('jquery'), '3.2.1', false);
      }
      add_action('wp_enqueue_scripts','cool_scripts');
      

      有关选择get_template_directory_uriget_stylesheet_directory_uri 的更多信息,请参阅this answer

      【讨论】:

      • 谢谢!我没有看到他使用 get_stylesheet_directory_uri() 而不是 get_stylesheet_uri()。我去看看你提供的链接。但是现在我的控制台上出现了另一个错误,上面写着“script.js?ver=3.2.1:3 Uncaught TypeError: $ is not a function”。正是在那一行代码上:“ $(".videowidth").hover(function(){ ”。我在网上看到有时你必须用 jQuery 替换 $ 才能使它工作。是真的吗?
      • 因为当我将脚本放入正文时,它会处理 HTML 文件。我想要实现的是当我将鼠标悬停在图标上时播放视频。我像在 HTML 文件上所说的那样对其进行了测试,但是当我在 wordpress 上对其进行测试时,它不起作用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-19
      • 2014-04-27
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多