我正在尝试向我的 wordpress 网站上的页面添加一些自定义 jQuery。
我使用了一个插件,它允许我将我的代码直接插入到特定页面的 head.php 文件中,但是代码没有运行,我只是收到错误
TypeError: $ is not a function
$(document).ready(function(){
我使用了 jQuery(function ($) { ...
来自这个问题的答案:TypeError: $ is not a function when calling jQuery function
<script>
jQuery(function ($(document).ready(function(){
jQuery(function ($)("#a").mouseover(function(){
jQuery(function ($)("#b").css("background-image", "url('https://oxfordriderwear.com/wp-content/uploads/2019/07/straight-black-cropped.jpg')");
});
jQuery(function ($)("#a1").mouseover(function(){
jQuery(function ($)("#b").css("background-image", "url('https://oxfordriderwear.com/wp-content/uploads/2019/07/straight-blue-cropped.jpg')");
});
jQuery(function ($)("#a2").mouseover(function(){
jQuery(function ($)("#b").css("background-image", "url('https://oxfordriderwear.com/wp-content/uploads/2019/07/straight-wash-cropped.jpg')");
});
jQuery(function ($)("#slim-a").mouseover(function(){
jQuery(function ($)("#slim-b").css("background-image", "url('https://oxfordriderwear.com/wp-content/uploads/2019/07/black-slim-rollover-cropped.jpg')");
});
jQuery(function ($)("#slim-a1").mouseover(function(){
jQuery(function ($)("#slim-b").css("background-image", "url('https://oxfordriderwear.com/wp-content/uploads/2019/07/blue-slim-rollover-cropped.jpg')");
});
jQuery(function ($)("#slim-a2").mouseover(function(){
jQuery(function ($)("#slim-b").css("background-image", "url('https://oxfordriderwear.com/wp-content/uploads/2019/07/blue-washed-slim-rollover-cropped.jpg')");
});
});
</script>
我想我的语法有误,但我不确定在哪里。
我还尝试通过 CDN 在代码中链接 jQuery,但这会阻止我页面上来自插件的其他 jQuery 元素正常工作,例如我的导航栏。
如果有人知道我做错了什么以及如何解决这个问题,我将不胜感激!
最佳答案
当我运行这段代码时,它抛出:
Uncaught SyntaxError: Unexpected token (
function ($)("#b")
…是语法错误。
您使用$
作为参数的名称并在函数内 作为变量。您已经跳过了使用 {
和 }
创建函数主体的部分以及放置函数名称 ($
) 在 (arguments)
之前。
您正在寻找的语法是(我已将其拆分为清晰的命名函数,而不是内联所有内容)。
function readyEventHandler ($) {
// Inside this function `$` is whatever is passed as the first argument
function mouseoverEventHandler(event) {
// Code to run on mouseover
}
const element = $("#a");
element.on("mouseover", mouseoverEventHandler);
}
jQuery(mouseoverEventHandler); // When the DOM is ready, this will call mouseoverEventHandler and pass the jQuery object in as the first argument
...或者所有内容都是内联的版本:
jQuery(function ($) {
$("#a").on("mouseover", function (event) {
// Code to run on mouseover
});
// Put other calls to `$` here. Don't create additional `jQuery(readyEventHandler)`s!
});
关于javascript - 将 jQuery 添加到 Wordpress head,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56899513/